Cocos2d js触摸事件

时间:2014-08-24 18:04:26

标签: javascript ios touch cocos2d-x cocos2d-js

我正在cocos2d-js中构建一个应用程序,我在听键盘事件时遇到了问题。我希望存在一个名为setKeyboardEnabled的方法,但是当我调用它时,我得到一个错误,即setKeyboardEnabled不是函数,我错过了什么吗?

var AnimationLayer = cc.Layer.extend({
ctor : function() {
    this._super();
    this.setKeyboardEnabled(true);
},


onKeyDown : function(key) {
   cc.log("action");
}
...
...
)}

当我尝试听触摸事件时,会发生同样的事情。

1 个答案:

答案 0 :(得分:6)

在Cocos2D v3中,处理事件的方式已经改变。要正确解释整个系统,您应该阅读New event manager in 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淡入淡出:

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 );
    }
)}