javascriptcraftyjs

How can I add event if x position is <= -50?


I'm moving a block with a tween:

  var block1 = Crafty.e('Block, 2D, Canvas, Color, Tween')
    .attr({x: 450, y: 140, w: 40, h: 200})
    .color('yellow')
    .tween({x: -50}, 3000);

How can I reset the position? So at x<=-50 then goes back to x=450? Can I bind it to the x position some way?


Solution

  • When the position is changed, a "Move" event is triggered. (This is part of the 2D component) So every time the object moves, you can just check it's current position and respond appropriately:

    var checkPos = function(){ 
        if (this.x<= -50)
            this.x = 450;
    };
    
    e.bind("Move", checkPos);
    

    If you want this to happen only once, use e.one instead of e.bind. If you want to start the tween over, you'll need a little bit more code, but it should be pretty clear how to do this.

    In your specific case, you can also listen to the "TweenEnd" event.