2

I have the following code:

var lion = game.add.sprite(2, 2,'lion');
var jump = game.add.tween(lion);
jump.to({x: 1000, y: 1000 }, 10000, Phaser.Easing.Linear.None);
// ... 
jump.start();

I create a sprite and would like to make it move between two points, here I am moving the lion from the top left corner to some point at the bottom right (1000,1000). Is it possible to add a bouncing motion to this movement?

At the moment the lion is moving in a straight line, but I would like to make it look as if the lion were jumping, like this:

jumping lion

How would I achieve this? Are tweens actually capable of producing a complex path like this?

cessor
  • 1,028
  • 11
  • 16
  • The easiest way would be to make a jumping animation that you play when you start the tween and stop when it ends – imcg Aug 16 '14 at 18:01

1 Answers1

4

Although the API is tricky and pooly documented (imho), I managed to find a good point to achieve this behavior. It took me 2 days to wrap my head around how tweening works and where to apply my changes.

When a tween is created, you can pass it an easing function. The easing I want applys to the Y axis only (the bouncing motion) and the movement to the right applys to the X axis only. Therefore I have to use two individual Tweens:

function vanHalen (v) { // Might as well jump
    game.debug.spriteInfo(lion, 32, 32);
    return Math.sin(v * Math.PI) * 1; 
};

function goLion() {
    var move = game.add.tween(lion);
    var jump = game.add.tween(lion);

    // "Move" is a linear easing function that will move the sprite to (1000,y). It takes the Lion 2 Seconds to get there.
    move.to({x: 1000}, 2000);

    // The Jump is a function that works on the y axis, uses a customized easing function to "bounce". 

    jump.to({y: 30}, 500, vanHalen, true, 0, Number.MAX_VALUE, 0);
    move.start();
};

The jumping starts automatically and never ends. When the movement to the right is over, the lion will continue bouncing in one place.

The easing function receives a progress value (between 0 and 1), that indicates how far the tween has moved (in percent).

cessor
  • 1,028
  • 11
  • 16