Search code examples
javascriptthree.jstweencreate.js

CreateJS chained animations not reaching target position


I am working on a project using Three.js and CreateJS. I have a problem with the animations, moving the same object multiple times. The first animation never reaches the target position, and so the next animations never start.

This is the js the code of one of my attempts:


import * as THREE from './libs/three.module.js'

let box, canvas, renderer, scene, camera;

function init(){
    setUpCamera();
    setUpScene();
    animate();
}
window.addEventListener('load', init);

function setUpCamera() {
    canvas = document.querySelector('.webgl')
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100)
    camera.position.set(0, 10, 15) // 0, 10, 5
    camera.rotation.x = (-40)*  Math.PI / 180

    renderer = new THREE.WebGLRenderer({
        canvas: canvas
    })

}

function setUpScene() {
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xbfe3dd);
    scene.add(camera);
    loadBox();
}

function loadBox(){
    let boxGeometry = new THREE.BoxGeometry(5, 5, 5);
    let boxMaterial = new THREE.MeshStandardMaterial( { color: 0x96f2af} );
    box = new THREE.Mesh( boxGeometry, boxMaterial);
    scene.add(box);
}

//This is the animation that won't work
//--------------------------------------------------
function animateBox(){
    console.log("box x position = " + box.position.x);
    createjs.Tween.get(box.position)
        .to({ x: 10 }, 300, createjs.Ease.linear) //this first animation never stops
        .to({ x: -10 }, 300, createjs.Ease.linear); //this second animation never starts
}
//--------------------------------------------------

function animate(){
    animateBox();
    renderer.render(scene, camera);[![enter image description here][1]][1]
    requestAnimationFrame(animate);
}

And this is the console output showing that the target position is never reached: Console output


Solution

  • It looks like you are creating a new tween every single frame. Tweens run their own requestAnimationFrame -- so you should be kicking off the tween one time, and not every frame.