javascriptcraftyjs

How to do a Tween in CraftyJS?


Alright, I'm at my wits end and I can't get CraftyJS to do a tween.

So what I wanna do is, everytime a Mushroom gets hit, I want to check if that mushroom has the component "Answer". If it exists, I will do nothing. Otherwise, I wanna display a big red box that fades away.

Crafty.c("Mushroom", {
        init: function() {
            this.addComponent("collision");
            this.collision();
            this.onhit("bullet",function(e) {
                this.destroy();
                e[0].obj.destroy();
                if(!this.has("Answer")) {
                    Crafty.e("2D, Tween, color, canvas")
                    .attr({alpha: 1.0, x: 170, y: 100, w:300, h:100})
                    .color("red")
                    .bind("enterframe", function() { //How do i actually get the box to fade?
                        this.tween({alpha: 0.5, x: 170, y: 100}, 30);
                    });
                }
            });
        }

Solution

  • You are binding the tween code execution to the EnterFrame event, which will cause the tween to start with each frame. Instead, you want to simply call the tween function on the entity you created, like so

     Crafty.e("2D, Tween, color, canvas")
                    .attr({alpha: 1.0, x: 170, y: 100, w:300, h:100})
                    .color("red")
                    .tween({alpha: 0.5, x: 170, y: 100}, 600);
    

    And the tween function will manage its own EnterFrame over the next 600 ms (30 frames), after which it will fire the TweenEnd event.

    (In old versions of Crafty, you specified the duration in frames instead of ms.)