Reputation: 1089
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
Upvotes: 9
Views: 20705
Reputation: 11
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
});
Upvotes: 1
Reputation: 17576
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
Upvotes: 18
Reputation:
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
Upvotes: 14