17 | Cocos2D-JS | How create objects with Chipmunk Physics
Opened this issue · 0 comments
Gurigraphics commented
17 | How create objects with Chipmunk Physics
Game.resources.js
Game.res = {
box_png : "res/box.png"
};
Game.g_resources = [];
for ( var i in Game.res ) {
Game.g_resources.push( Game.res[i] );
}
Game.scenes.js
Game.scenes[1].extend = cc.Scene.extend({
onEnter:function () {
this._super();
layer = new Game.layers[1].extend();
layer.init();
this.addChild( layer );
}
});
Game.layers.js
Layer extend
Game.layers[1].extend = cc.Layer.extend({
init:function () {
this._super();
var game = this;
Game.startPhysics();
Game.startPhysicsDebug( game );
Game.addPhysicsBodies( game );
game.scheduleUpdate();
},
update:function(dt){
world.step(dt);
for( var i = coliders.length - 1; i >= 0; i-- ){
coliders[i].image.x = coliders[i].body.p.x
coliders[i].image.y = coliders[i].body.p.y
var angle = Math.atan2( -coliders[i].body.rot.y, coliders[i].body.rot.x );
coliders[i].image.rotation = angle * 57.2957795;
}
}
});
Start physics
Game.startPhysics = function(){
world = new cp.Space();
world.gravity = cp.v(0, -500);
coliders = [];
}
Start physics debug
Game.startPhysicsDebug = function( game ){
var debugDraw = cc.PhysicsDebugNode.create( world );
debugDraw.setVisible( true );
game.addChild( debugDraw );
}
Add physics bodies
Game.addPhysicsBodies = function( game ){
var config = {
posX: 320,
posY: 20,
width: 640,
height: 20,
isDynamic: false,
sensor: false,
spriteImage: "null",
type: "ground",
id: "tag"
}
game.addBody( config );
var config = {
posX: 320,
posY: 480,
width: 64,
height: 64,
isDynamic: true,
sensor: false,
spriteImage: Game.res.box_png,
type: "box",
id: "tag_1"
}
game.addBody( config );
var config = {
posX: 290,
posY: 64,
width: 64,
height: 64,
isDynamic: true,
sensor: false,
spriteImage: Game.res.box_png,
type: "box",
id: "tag_2"
}
game.addBody( config );
}
Method addBody
Game.layers[1].extend.prototype.addBody = function( config ){
if( config.isDynamic ) var body = new cp.Body( 1, cp.momentForBox( 1, config.width, config.height ) );
else var body = new cp.Body( Infinity, Infinity );
body.setPos( cp.v( config.posX, config.posY) );
if( config.isDynamic ) world.addBody( body );
Game.addPhysicsShapes( body, config );
}
Add physics shapes
Game.addPhysicsShapes = function( body, config ){
var shape = new cp.BoxShape( body, config.width, config.height );
shape.setFriction(1);
shape.setElasticity(0);
shape.name = config.type;
shape.image = Game.addPhysicsSprites( config );
shape.id = config.id;
shape.sensor = config.sensor;
world.addShape( shape );
coliders.push( shape );
}
Add physics sprites
Game.addPhysicsSprites = function( config ){
var bodySprite = cc.Sprite.create( config.spriteImage );
layer.addChild( bodySprite, 0 );
bodySprite.setPosition( config.posX, config.posY );
return bodySprite
}