09 | Cocos2D-JS | How to use touch event
Opened this issue · 0 comments
Gurigraphics commented
09 | How to use touch event
Game.layers.js
Edit the Game.layers.js
Add to sprite that has been extended the listener.
In a complex project the ideal is to create another file Game.listeners.js to isolate the events in a separate file. And then import into projects.json
var sprite2 = cc.Sprite.extend({
ctor:function() {
this._super();
this.initWithFile("HelloWorld.png");
this.setScale(0.5);
cc.eventManager.addListener(listener.clone(), this);
}
});
var listener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true,
onTouchBegan: function (touch, event) {
sprite2 = event.getCurrentTarget();
var location = sprite2.convertToNodeSpace(touch.getLocation());
var targetSize = sprite2.getContentSize();
var targetRectangle = cc.rect(0, 0, targetSize.width, targetSize.height);
if (cc.rectContainsPoint(targetRectangle, location)) {
layer.removeChild(sprite2);
var tag = sprite2.getTag();
}
}
});
The same listener can be added for different sprites.
To know which sprite was clicked use the tags:
var tag = sprite2.getTag ();
Events:
onTouchBegan: on press
onTouchEnded: on release
onTouchMoved: on press and move
onTouchCancelled: on canceling