chipmunkLayer和上一篇的实现方式几乎一致,只是两种引擎有差别,
var chipmunkLayer = cc.Layer.extend({ size: null, space: null, _debugNode: null, box: null, downUpAction: null, onEnter: function() { this._super(); this.size = cc.director.getWinSize(); this.space = new cp.Space(); //初始化物理世界 this.initPhysics(); //初始化正方形 this.initBoxWithBody(); this.init(); //背景 var bg = cc.LayerColor.create(cc.color(0, 0, 0)); bg.attr({ anchorX: 0, anchorY: 0, x: 0, y: 0 }); this.addChild(bg); }, init: function() { cc.sys.dumpRoot(); cc.sys.garbageCollect(); this.scheduleUpdate(); }, initPhysics: function() { //初始化物理环境,增加边界 var winSize = this.size; var space = this.space; var staticBody = space.staticBody; space.gravity = cp.v(0, -980); //重力 space.sleepTimeThreshold = 0.5; //休眠临界时间 space.collisionSlop = 0.5; // //walls 四个边界 var walls = [ new cp.SegmentShape(staticBody, cp.v(0, 0), cp.v(winSize.width, 0), 0), // bottom new cp.SegmentShape(staticBody, cp.v(0, winSize.height), cp.v(winSize.width, winSize.height), 0), // top new cp.SegmentShape(staticBody, cp.v(0, 0), cp.v(0, winSize.height), 0), // left new cp.SegmentShape(staticBody, cp.v(winSize.width, 0), cp.v(winSize.width, winSize.height), 0) // right ]; for (var i = 0; i < walls.length; i++) { var shape = walls[i]; shape.setElasticity(1); //弹性 shape.setFriction(0); //摩擦 //space.addStaticShape( shape ); space.addShape(shape); } }, initBoxWithBody: function() { var winSize = this.size; //物体的定义 var mass = 1; var boxWidth = 32; var body = new cp.Body(mass, cp.momentForBox(mass, boxWidth, boxWidth)); body.setPos(cc.p(winSize.width / 2, winSize.height / 2)); this.space.addBody(body); var shape = new cp.BoxShape(body, boxWidth, boxWidth); shape.setElasticity(1); //弹性 shape.setFriction(0); //摩擦 shape.setCollisionType(1); shape.setLayers(3); this.space.addShape(shape); //创建一个箱子 this.box = cc.PhysicsSprite.create(res.BOXPNG, cc.rect(0, 0, boxWidth, boxWidth)); this.box.setBody(body); this.addChild(this.box, 1); }, update: function(dt) { // chipmunk step this.space.step(dt); }, }); chipmunkLayer.scene = function() { var scene = cc.Scene.create(); scene.addChild(new chipmunkLayer()); return scene; }
源码地址:http://pan.baidu.com/s/1ntVX6nZ