Creating a floating effect for a cube in Three.js involves applying specific techniques and animations

I've been experimenting with making a Boxgeometry float in three.js, but my attempts have not been successful so far. I tried using setTimeout to achieve the floating effect, but it didn't work as expected. Here is what I attempted:

function animate() {
  requestAnimationFrame( animate );

  cube.position.y += 0.01
  setTimeout(function(){
    cube.position.y += -0.02
  }, 10000);

  renderer.render( scene, camera );
}

Instead of smoothly floating, the cube just moves up and down in a choppy manner.

Can anyone suggest a better way to create a smooth floating animation for the cube?

Answer №1

Utilizing trigonometric functions such as sin() can produce a simple floating effect.

let camera, scene, renderer;
let clock, mesh;

initialize();
animate();

function initialize() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 1;

  scene = new THREE.Scene();
  
  clock = new THREE.Clock();

  const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
  const material = new THREE.MeshNormalMaterial();

  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

    const time = clock.getElapsedTime();
  
  mesh.position.y = Math.cos( time ) * 0.2;
 
  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9de9f5eff8f8ddadb3acaea9b3ad">[email protected]</a>/build/three.min.js"></script>

The animations you create will vary depending on how you set up the calculations and combine trigonometric functions.

For even more versatility, consider using animation libraries like GSAP or Tween.js to access a wide range of easing functions easily.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

Having trouble with changing text in a link with an onclick event?

When I click on the link, I want the text to change to the second span. However, this functionality is not working. Code var reload = false; $('#change').click(function() { reload = !reload; $('#change').click(function() { ...

Preventing Body Overflow Without Affecting Iframe Overflow in Meteor.js

Currently, I am working on a project using Meteor for a Point of Sale (POS) system. For those unfamiliar with it, Meteor is a framework that allows for the use of JavaScript, jQuery, and various other web app scripting languages. The goal of this applicati ...

Make the browser interpret XHR response as gzip encoding

I am currently working on a client-side JavaScript application that is responsible for downloading relatively large JSON datasets for visualization. My goal is to compress these datasets in advance using gzip to conserve space and decrease bandwidth consum ...

Attempting to create a responsive Boxplot in Three.js

I created a basic three.js boxplot that loads individual jpg images for each mesh (bar). The boxplot appears fine on desktop, but is stretched/distorted on mobile devices. Is there a recommended approach to make it responsive? For simplicity, I will use e ...

Looping through a nested for loop within an HTML table

I am currently working on generating a dynamic table using Lists of varying sizes. My first list is a List of Cars List<Car>. I have successfully placed the names of different car companies in the header. Next, I have a List<List<CarSales>& ...

Utilizing Axios recursion to paginate through an API using a cursor-based approach

Is there a way to paginate an API with a cursor using axios? I am looking to repeatedly call this function until response.data.length < 1 and return the complete array containing all items in the collection once the process is complete. Additionally, I ...

Is Next.js Dynamic Routing Failing You?

Recently, I attempted to implement Dynamic routing for a recipe app but encountered an issue where the page was not found. This problem has left me puzzled as I am fairly inexperienced with TypeScript, although not with React. // pages/recipes/[recipeId].t ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

Filter the ng-repeat in Angular based on the model's value

Within my "Saving" model, there is a field called "Retailer". I want to implement an ng-repeat directive that displays only items with the same "Retailer" value. Essentially, I am attempting to rectify this issue. <div ng-repeat="saving in savings | ...

Exploring the Functionality of Chaining in JQuery and Understanding its Inner Workings

I have a question and I am looking for the best answer. Hopefully, someone in our group can provide it. Most of you are familiar with jQuery chaining. It allows us to attach multiple events to an HTML element using just one statement. For example: $(&ap ...

I'm puzzled as to why, but my code seems to be causing an issue with the command prompt, possibly due

Recently, I've been taking on the challenges of Advent of Code. Day 2 has me stumped, as there's a peculiar issue with the code when running it through node.js in the command prompt: const fs = require("fs"); var valid = fs.readFileSync("inpu ...

Performing ajax requests with nested ajax calls within a loop

I'm facing a particular issue. My code structure involves nested/foreach loops with ajax calls like below: var children = []; $.fn.ajaxHelper.loadAjax({ url: someUrlReturningJsonOfChildren, cache: true, callback: function(options) { ...

Vue.js computed property fails to initiate

Why is the Vue JS computed property not triggered with this markup? <!-- language: lang-html --> <p>£{{plant_price}}</p> <div v-if="selected.plant.variations.length > 0 "> <select v-model="selected.plant.selected_ ...

Vue2 data vanishing mysteriously

I created a basic webpage using vue2 to convert binary numbers to decimal. However, I encountered an issue where the data disappears when submitting the binary value in an HTML form. <template> <div class="bar"> <input id="str" t ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

Error encountered: `prisma.product.findMany()` function call is not valid when the application is deployed on V

After adding Prisma to my site, I encountered an error while trying to deploy it. Unfortunately, I am unsure how to resolve this issue. PrismaClientKnownRequestError: Invalid `prisma.product.findMany()` invocation: Raw query failed. Code: `unknown`. Messa ...

Unable to upload a file to an email using the mandrillapp JSON API

Having trouble sending an email with an attached document via the Mandrillapp JSON API using the method send-template in JavaScript. The email sends successfully, including images attached to the images array. However, documents sent in the attachements ar ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...