Drag a sprite on touch

Drag a sprite on touch
0.0 0


I’ve been looking all over the place for clear instructions on how to move a sprite around the screen when you click and drag it. Right now I’ve registered when a touch begins, but cannot register the touch movement.

Here is my code:

ctor:function () {

init:function () {

        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: false,
        onTouchBegan: function (touch, event) {

            var target = event.getCurrentTarget();

            var locationInNode = target.convertToNodeSpace(touch.getLocation());
            var s = target.getContentSize();
            var rect = cc.rect(0, 0, s.width, s.height);
            //Check the click area
            if (cc.rectContainsPoint(rect, locationInNode)) {
                cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y);
                target.opacity = 180;
                return true;
            return false;


        onTouchMove:function (touch, event) {
            cc.log("mouse moved")
    }, this);

I’m very new to cocos2d js, so could you tell me if I’m roughly on the right track.

I am also wondering whether it would be a good idea to take a different approach and add the event handler directly to the sprite instead of the layer. that way I could avoid checking if the touch hit the sprite, and also have the sprite update position itself.
Doing it like that may become less efficient though with multiple different types of sprites.

Sorry if that didn’t make sense, just let me know and I’ll try to clarify it. Thanks for your help in advance.


Use getPosition and setPosition in your onMove and change it by a small delta. I have C++ code I use but not JS. Sorry.


Thanks for your help! I got it working