在 Cocos2D v3 中,处理事件的方式发生了变化。要正确解释整个系统,您应该阅读Cocos2d-Html5 v3.0 中的新事件管理器。
简而言之,如果您曾经拥有:
var AnimationLayer = cc.Layer.extend({
ctor : function() {
this._super();
this.setKeyboardEnabled(true);
},
onKeyDown : function(key) {
cc.log("action");
}
...
...
)}
你必须把它变成类似的东西:
var AnimationLayer = cc.Layer.extend({
ctor : function() {
this._super();
cc.eventManager.addListener({
event: cc.EventListener.KEYBOARD,
onKeyDown : function(key) {
cc.log("action");
}
}, this);
},
...
...
)}
起初这听起来有点复杂,但这种新机制允许您将这些事件侦听器附加到任何类型的cc
节点,而不仅仅是层。因此,例如,当鼠标在 Sprite 上方时,您可以执行以下操作以使 Sprite 淡出:
var hoverHandler = cc.EventListener.create({
event: cc.EventListener.MOUSE,
onMouseMove: function (event) {
var target = event.getCurrentTarget();
var locationInNode = target.convertToNodeSpace(event.getLocation());
var s = target.getContentSize();
var rect = cc.rect(0, 0, s.width, s.height);
if (cc.rectContainsPoint(rect, locationInNode)) {
cc.log("It's hovering! x = " + locationInNode.x + ", y = " + locationInNode.y);
target.opacity = 180;
return true;
} else {
target.opacity = 255;
return false;
}
}
});
var MyLayer = cc.Layer.extend({
init: function() {
this._super();
var mySpriteThatFadesWhenHovered = cc.Sprite.create(...);
this.addChild(mySpriteThatFadesWhenHovered);
cc.eventManager.addListener(hoverHandler.clone(), mySpriteThatFadesWhenHovered );
}
)}