Book Image

Learning Cocos2d-JS Game Development

By : Emanuele Feronato
Book Image

Learning Cocos2d-JS Game Development

By: Emanuele Feronato

Overview of this book

Table of Contents (18 chapters)
Learning Cocos2d-JS Game Development
Credits
Foreword
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Creating Your Own Blockbuster Game – A Complete Match 3 Game
Index

Using your own graphic assets


Just as in the previous chapter, we will add graphics when we add a body, then update their position and rotation according to its body position and rotation.

First, update the addBody function:

addBody: function(posX,posY,width,height,isDynamic,spriteImage,type){
  if(isDynamic){
    var body = new cp.Body(1,cp.momentForBox(1,width,height));
  }
  else{
    var body = new cp.Body(Infinity,Infinity);
  }
  body.setPos(cp.v(posX,posY));
  var bodySprite = cc.Sprite.create(spriteImage);
  gameLayer.addChild(bodySprite,0);
  bodySprite.setPosition(posX,posY);
  if(isDynamic){
    world.addBody(body);
  }
  var shape = new cp.BoxShape(body, width, height);
  shape.setFriction(1);
  shape.setElasticity(0);
  shape.name=type;
  shape.image=bodySprite;
  world.addShape(shape);
  shapeArray.push(shape);
}

This works in the same way as we saw with Box2D: a sprite is added to the game and is saved in a custom shape attribute—in this case, image.

To update the sprite's position...