6

I'm using three.js and animated some Objects. I animated the object by using the animate() function of three.js. Basically something like that:

function animate(){
    object.position.z++;
}

Unfortunatlly this is called every rendered frame. So on each device with different framerates the speed of my object is different. Is there a way to make this depending on seconds or miliseconds?

thanks

3 Answers 3

17

There's also THREE.Clock() in three.js:

var clock = new THREE.Clock();
var speed = 2; //units a second
var delta = 0;

render();
function render(){
  requestAnimationFrame(render);

  delta = clock.getDelta();
  object.position.z += speed * delta;

  renderer.render(scene, camera);
}

jsfiddle example r86

1
  • @JeffProd I mean "speed" :) Apr 22, 2020 at 14:21
11

requestAnimationFrame passes the time since the page was loaded to the callback. I usually prefer to do my math in seconds but the time passed in is in milliseconds so

let then = 0;
function animate(now) {
  now *= 0.001;  // make it seconds

  const delta = now - then;
  then = now;

  object.position.z += delta * speedInUnitsPerSecond;

  ...

  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

ps: I'm surprised this isn't already on stackoverflow. It probably is somewhere. Certainly requestAnimationFrame has been covered, maybe just not in the context of three.js.

There is this: Best options for animation in THREE.JS

1

You can use TWEEN(a js lib for Three). This is a tutorial for TWEEN: http://learningthreejs.com/blog/2011/08/17/tweenjs-for-smooth-animation/

You can use it very simply:

  new TWEEN.Tween(object.position).to(targetPos, 200).start().onComplete(()=>{
      //Do something when action complete
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.