HaxePunk LinearTween Example

I want to share some example code that describes how to do a simple LinearPath tween w/ the HaxePunk Library



Edit (2013-03-06): fixed signature for callback/event listener and move this to it’s own post

HaxePunk Tweens

While exploring HaxePunk, I discovered that sometimes documentation can be a little lacking. So I just wanted to write this down for future reference:

Tweening is pretting simple. Each com.haxepunk.World and com.haxepunk.Entity is what is called a Tweener (_com.haxepunk.Tweener_).

There are already a bunch of different tweens in the com.haxepunk.tweens.* namespace.

Specifically, if you want to do motion, based on a path a character has to take, you can use the com.haxepunk.tweens.motion.LinearPath tween.

In the begin() method of an Entity you can do something like this:

// assuming _movetween is defined elsewhere in the class, and
// com.haxepunk.tweens.motion.LinearPath as been imported
_movetween = new LinearPath(tweenEnds);
_movetween.addPoint(this.x, this.y); // starting point
_movetween.addPoint(this.x+32, this.y); // left 32px
_movetween.addPoint(this.x+32, this.y-32); // left 32px, up 32px, ending point
_movetween.setMotion(0.5); // do this in .5 seconds

The tweenEnds parameter is just a reference to a function called when the tween ends:

function tweenEnds(event:Dynamic) {
    // set the final x/y values here since the update() method,
    // as detailed below, won't set the final variables since the IDLE
    // state is being started
    this.x = _movetween.x;
    this.y = _movetween.y;
    state = IDLE;

To call this, you just put something like the following in an Entities update() method:

if(startmoving) {
    state = MOVING;
    _movetween.start(); // reset the tween to the beginning and start running it
else {
    // the tween will contain the x and y values that are desired at a particular
    // point in time during the tween, and remember, you don't want to set the x
    // and y values immediately after calling start() on the tween -- it'll give
    // you a "hiccup" where your Entity moves to the final spot, then jumps
    // back and progresses allong the LinearPath.
    this.x = _movetween.x;
    this.y = _movetween.y;

Hopefully this has given a little insight for someone (like my future self) on how to use HaxePunk tweens.