Search code examples
kineticjs

Move shape up on mouse click in KineticJS


I'm recreating this classic helicopter game:

http://www.play-helicopter-game.com/

I can't figure out what I should be using to recreate the upward motion that occurs when the user holds down the mouse. Does anybody know what I should be using in KineticJS to recreate this effect on a shape?

I considered tween but it seems to only work if you're moving the shape to predetermined coordinates.

Please let me know if you can help. Thanks!


Solution

  • Here's is some starting code for you to experiment with...

    As you've discovered a Tween will only move something from A to B without much control.

    Instead, create an animation loop that changes your helicopter "Y" property each frame

    var helo;
    var heloY=50;
    var direction=0;
    
    var animation=new Kinetic.Animation(function(){
        helo.setY(heloY);
        heloY+=direction*1;
    },layer);
    

    Listen for mousedown events on your helicopter and set the direction to up

    helo.on("mousedown",function(){direction=-1;});
    

    Listen for mouseup and mouseout events on your helicopter and set the direction to down

    helo.on("mouseleave mouseup",function(){direction=1;});