Search code examples
javascripthtml5-canvascreatejsanimate-cc

How to make object jump to cursor/touch position on mousedown?


based on the createjs drag and drop demo, I'm trying to make it so that the circle jumps to the position of the cursor/touch on mousedown.

I managed to make the dragging work, but no idea how to make the circle jump to position.

createjs.Touch.enable(stage);

this.circle_mc.on("pressmove", function (evt) {
    var point = stage.globalToLocal(evt.stageX, evt.stageY)
    evt.currentTarget.x = point.x;
    evt.currentTarget.y = point.y;
    stage.update();
});

Can anyone help it do something like this?

enter image description here

Update: Managed to get it to work using this code in animate:

var _this = this;

stage.on("stagemousedown", function (evt) {
    var point = stage.globalToLocal(evt.stageX, evt.stageY)
    _this.circle_mc.x = point.x;
    _this.circle_mc.y = point.y;

    var moveAround = stage.on("stagemousemove", function (evt) {
        var point = stage.globalToLocal(evt.stageX, evt.stageY)
        _this.circle_mc.x = point.x;
        _this.circle_mc.y = point.y;
    });

    stage.on("stagemouseup", function (evt) {
        stage.off("stagemousemove", moveAround)
    }, null, true)
});

Solution

  • You can do this easily, but you have to re-make the dragmove, since by default it requires the mousedown on an object to kick it off. You also must reference the target directly instead of relying on an event target.

    stage.on("stagemousedown", function(e){
        s.x = e.stageX; s.y = e.stageY;
      
      // Handle move
      var evt = stage.on("stagemousemove", function(e) {
        // Set to mouse position each move
        s.x = e.stageX; s.y = e.stageY;
      });
      
      // Handle release
      stage.on("stagemouseup", function(e) {
        stage.off("stagemousemove", evt)
      }, null, true)
    });
    

    Here is a quick fiddle with better comments. https://jsfiddle.net/lannymcnie/fn3gve74/1/