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...