Home > Back-end >  How to make floating effect for cube Three.js
How to make floating effect for cube Three.js

Time:11-01

So I'm trying to make a Boxgeometry float in three.js, I try doing it with setTimeout but it didn't work, here is what I try.

function animate() {
  requestAnimationFrame( animate );

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

  renderer.render( scene, camera );
}

It only goes up and down, that doesn't look like it is floating.

how can I make a floating animation for the cube?

CodePudding user response:

By using trigonometric functions like sin() you can achieve a basic floating effect.

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

init();
animate();

function init() {

  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/[email protected]/build/three.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Depending on how you parametrize the computation and how you combine trigonometric functions you can implement quite different animations.

Also consider to use an animation library like GSAP or Tween.js to easily access a wide range easing functions.

  • Related