Tween JS Basics on Three JS Cubes
I am new to Tween JS and am trying to do a simple animation moving to the right using Tween.
Below is my code in init function (I am using three JS):
var geometry = new THREE.CylinderGeometry( 200,200, 200, 4, 0 );
var material = new THREE.MeshPhongMaterial( { ambient: 0xf0f0f0, color: 0x006699, specular: 0x006699, shininess: 60, shading: THREE.FlatShading } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene.add( mesh );
var tween = new TWEEN.Tween( { x: 0, y: 0 } )
.to( { x: 400 }, 2000 )
.easing( TWEEN.Easing.Elastic.InOut )
.onUpdate( function () {
mesh.position.x = Math.round( this.x );
} ).start();
And my animation function:
requestAnimationFrame(animate);
renderer.render(scene, camera);
TWEEN.update();
update();
The cube is there, but the twin does not work. Am I missing something?
source to share
The following is what I did with my scene.
-
Create a separate render () function
-
Place the TWEEN code in a function that you can call. You want to remove all TWEENs at the start of this function. I'm not really sure why, but I learned about this from the tutorial code.
-
In the TWEEN function, call the render function on update.
-
Call TWEEN.update on your animation through the animation loop without stopping. Note: render () will be called every time you update TWEEN.
Below is the skeleton code. Check if this might apply to your program:
//TWEEN function
function moveObject( ) {
TWEEN.removeAll();
new TWEEN.Tween( { x: 0, y: 0 } )
.to( { x: 400 }, 2000 )
.easing( TWEEN.Easing.Elastic.InOut )
.onUpdate( render )
.start();
};
//NON-STOP animation loop
function animation(){
requestAnimationFrame(animate);
TWEEN.update();
}
//Render function
function render(){
renderer.render(scene, camera);
}
Hope it helps.
source to share