Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js animate in real time

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

like image 321
tinytree Avatar asked Jul 27 '17 07:07

tinytree


People also ask

Can you animate using JavaScript?

Animation CodeJavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.

Is Three js based on WebGL?

three. js is a JavaScript-based WebGL engine that can run GPU-powered games and other graphics-powered apps straight from the browser. The three. js library provides many features and APIs for drawing 3D scenes in your browser.


3 Answers

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

like image 166
prisoner849 Avatar answered Oct 19 '22 12:10

prisoner849


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

like image 11
gman Avatar answered Oct 19 '22 12:10

gman


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
  });
like image 1
Điệp Trần Avatar answered Oct 19 '22 10:10

Điệp Trần