Cocos2d js touch events

Edgar Zakaryan picture Edgar Zakaryan · Aug 24, 2014 · Viewed 9.5k times · Source

I'm building an app in cocos2d-js, and I've got a problem with listening to keyboard events. I expect a method called setKeyboardEnabled to exists but when I call it i get an error that setKeyboardEnabled is not a function, Am I missing something?

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


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

The same thing happens when I try to listen to touch events.

Answer

Sebastián Vansteenkiste picture Sebastián Vansteenkiste · Aug 25, 2014

In Cocos2D v3 the way events are handled has changed. For a proper explanation of the whole system you should read New event manager in Cocos2d-Html5 v3.0.

In short, if you used to have:

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

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

You have to turn it into something like:

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

        cc.eventManager.addListener({
            event: cc.EventListener.KEYBOARD,
            onKeyDown : function(key) {
                cc.log("action");
            }
        }, this);
    },        

    ...
    ...
)}

This can sound a bit complicated at first, but this new mechanism allows you to attach these event listeners to any kind of cc node, not just layers. So for example you could do something like this to make a Sprite fade when the mouse is above it:

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