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
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.
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.
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
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
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With