cocos2d-html5 Sprite 注册点击事件
在 cocos2d-html5, 发现 Sprite 类没有点击事件,需要注册点击的代理, 才能接受点击事件。下面一段代码写了一个可以接受点击事件的 DemoSprite 类。
var DemoSprite = cc.Sprite.extend({
_touchBegan: false,
_touchEnabled: true,
ctor: function (image) {
this._super();
this.init(image);
},
onEnter: function () {
cc.Director.getInstance().getTouchDispatcher()._addTargetedDelegate(this, 0); // 当Sprite加载完后, 注册点击事件(有好几种注册的方式,在这里就不一一介绍了)。
this._touchEnabled = true;
this._super();
},
onExit: function () {
cc.Director.getInstance().getTouchDispatcher()._removeDelegate(this);
//当Sprite退出后,取消点击事件的注册。
this._touchEnabled = false;
this._super();
},
touchRect: function () {
return this.getBoundingBoxToWorld();
},
onTouchBegan: function (touch, event) {
if (cc.rectContainsPoint(this.touchRect(), touch.getLocation())) {
//当点击在 Sprite 范围内时,执行。
//在这里处理点击事件。
this._touchBegan = true;
return true; //返回true, 才会执行 onTouchEnded方法。
}
return false;
},
onTouchEnded: function (touch, event) {
if (this._touchBegan) {
this._touchBegan = false;
}
}
});
ps: cocos2d-html5 她真的很美。