Search code examples
tweenjs

Tweenjs randomized values in repeating tween


Exploring Tweenjs. I just want to move some circles randomly around the stage. I understand that all tweening is "deterministic," meaning that it uses pre-calculated values for speed. So I have two functions that call each other. The 2nd function is called when the tween completes. Unfortunately, I'm getting a call stack overflow error.

HOw can i make this run forever and move circles endlessly to random positions?

function tweenPosition(circle) {
    var xPosition = Math.random() * stageWidth
    var yPosition = Math.random() * stageHeight

    createjs.Tween.get(circle, {loop: false}).wait(0).to({x: xPosition, y: yPosition}, 1000, createjs.Ease.sineInOut).onComplete(tweenPositionComplete(this, xPosition, yPosition))
}
function tweenPositionComplete(circle, x, y) {
    circle.x = x
    circle.y = y
    tweenPosition(this)
}

Solution

  • In the Tween instance inside the tweenPosition function, instead of using the onComplete method, use the call method, and add it at the end of that Tween instance.

    call (callback, [params], [scope])
    

    In the case of your code:

    .call(tweenPositionComplete, [circle, xPosition, yPosition])
    

    Your Tween will look like this:

    createjs.Tween
            .get(circle, {loop:false})
            .wait(0)
            .to({x:xPosition, y:yPosition}, 1000, createjs.Ease.sineInOut)
            .call(tweenPositionComplete, [circle, xPosition, yPosition]); 
    

    In this fiddle you can see it in action.

    See also: Tween Class (TweenJS API)