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)); 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,// bottom new cp.SegmentShape(staticBody,winSize.height),// top new cp.SegmentShape(staticBody,// left new cp.SegmentShape(staticBody,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); 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,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; }
注意:我用的3.9版本的个别地方改变了。
源码地址:http://pan.baidu.com/s/1ntVX6nZ