box2d and keyboard example

Hello,

First of all congrats for the work you done with the JS version, I like it so far.

  1. I want to start working with the box2djs but I don’t see any example, how to link it with the cc.node objects, and how to implement the mechanics/collisions/movings etc.

  2. Second question is about controller, I see that cocos2d uses a different aproach (on update the object you check if the key is pressed - and in the Layer with the functions onKeyDown, is like this in the only game I could find https://github.com/ShengxiangChen/MoonWarriors/blob/master/MoonWarriors/src/GameLayer.js ), I suspect update is based on fps/layer/tick update
    But I see that there are some classes - cc.KeyboardDelegate() , dispatcher and handler, how can I use these ?

  3. Global, what is the best standard to keep the global data, like player data, action history, other players data, etc, I use a regular global JS object or the framework provides us with a global singleton class like cc.director ?

Thanks,

Hi,

You should check out this example:
http://www.cocos2d-x.org/boards/19/topics/16487?r=19128

This example really helped me a lot in the beginning.

I use the built in keyboard handler of the cc.Layer.
you have to activate it as follows: this.setKeyboardEnabled(true); (in the example the touch events are added using this.setTouchEnabled(true))

then I handle the keyboard events like this:

onKeyUp: function(e){
        switch(e){
            case cc.KEY.left:
                this.isLeftPressed = false;
                break;
            case cc.KEY.right:
                this.isRightPressed = false;
                break;
            case cc.KEY.up:
                this.isUpPressed = false;
                break;
        }
    },
    onKeyDown: function(e){
        switch(e){
            case cc.KEY.left:
                this.isLeftPressed = true;
                break;
            case cc.KEY.right:
                this.isRightPressed = true;
                break;
            case cc.KEY.up:
                this.isUpPressed = true;
                break;
     }
}

And then in your stepper you can move your box2d objects

this is how I got it to work:

var vel = playerSprite.body.GetLinearVelocity();
if(this.isLeftPressed){

     if(vel.x>-this.maxVelocity){
          vel.x -= 0.5;
     }else{
          vel.x = -this.maxVelocity;
     }
}

I’m still trying to find that myself.

Hope this helps.

Happy coding