javascriptcocos2d-js

Cocos2d JS / Cocos Creator add touch listener to specific node


I want to drag a specific sprite on touch. I wonder if I can add event listeners only to a specific node, so I dont have to check which node was touched before starting the specific dragging function for each node. The following code does also "fire" when touched outside of the specific node.

this.directionDial = new cc.Node()
    this.directionDial.graphics = this.directionDial.addComponent(cc.Graphics)
    this.node.addChild(this.directionDial)
this.directionDial.graphics.lineWidth = 2;
    this.directionDial.graphics.strokeColor = cc.Color.RED;
    this.directionDial.graphics.circle(80, 0, 10);
    this.directionDial.graphics.stroke();

    var _this = this;

    // Touch control 
    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            //do something
            _this.forceDirection = 1;
            _this.displayDirection()
            return true;
        }
    }, this.directionDial); 

Solution

  • Yes, using Cocos Creator you can do something like:

    this.node.on(cc.Node.EventType.TOUCH_START, this.methodToBeCalled, this);