[cocos2d-js]chipmunk例子(一)

时间:2023-11-10 18:42:56
initChipmunk:function() {
this.space = new cp.Space(); this.setupDebugNode(); //设置空间内刚体间联系的迭代计算器个数和弹性关系迭代计算器个数.
//chipmunk使用迭代计算器计算出空间内物体的受力关系.
//它建立一个大列表存放物体间所有的碰撞,连接等相互影响关系.根据实际情况传递某些相互作用.
//传递相互作用的数取决于迭代器的个数,每次迭代都使计算结果更精确.
//如果进行了过多的迭代,虽然物理影响效果会更好,但是这也会消耗过多的cpu处理时间.
//如果进行的迭代太少,物理模拟效果会不精确,或者使本该静止的物体没能静止下来.
//使用迭代器的个数在于平衡CPU性能和物理模拟精确度之间权衡.
this.space.iterations = ;
//设置空间的重力向量
this.space.gravity = cp.v(, -);
// 休眠临界时间
this.space.sleepTimeThreshold = 0.5;
this.space.collisionSlop = 0.5; this.addFloor();
this.addWalls(); var width = ;
var height = ;
var mass = width * height * /;
var rock = this.space.addBody(new cp.Body(mass, cp.momentForBox(mass, width, height)));
rock.setPos(cp.v(, ));
rock.setAngle();
var shape = this.space.addShape(new cp.BoxShape(rock, width, height));
shape.setFriction(0.3);
shape.setElasticity(0.3); var radius = ;
mass = ;
var body = this.space.addBody(new cp.Body(mass, cp.momentForCircle(mass, , radius,cp.v(, ))));
body.setPos(cp.v(, ( * radius + )));
var circle = this.space.addShape(new cp.CircleShape(body, radius,cp.v(, ))); circle.setElasticity(0.8);
circle.setFriction(); var ramp = this.space.addShape(new cp.SegmentShape(this.space.staticBody,cp.v(, ),cp.v(, ), ));
ramp.setElasticity(); // 弹性
ramp.setFriction(); // 摩擦
ramp.setLayers(NOT_GRABABLE_MASK); var sprite = this.createPhysicsSprite(cc.p(,));
this.addChild(sprite);
},
addFloor:function() {
var floor = this.space.addShape(new cp.SegmentShape(this.space.staticBody,cp.v(, ),cp.v(, ), ));
floor.setElasticity();
floor.setFriction();
floor.setLayers(NOT_GRABABLE_MASK);
},
addWalls:function() {
var wall1 = this.space.addShape(new cp.SegmentShape(this.space.staticBody,cp.v(, ),cp.v(, ), ));
wall1.setElasticity();
wall1.setFriction();
wall1.setLayers(NOT_GRABABLE_MASK); var wall2 = this.space.addShape(new cp.SegmentShape(this.space.staticBody,cp.v(, ),cp.v(, ), ));
wall2.setElasticity();
wall2.setFriction();
wall2.setLayers(NOT_GRABABLE_MASK);
},
createPhysicsSprite:function( pos ) {
var body = new cp.Body(, cp.momentForBox(, , ) );
body.setPos( pos );
this.space.addBody( body );
var shape = new cp.BoxShape( body, , );
shape.setElasticity( 0.5 );
shape.setFriction( 0.5 );
this.space.addShape( shape ); var sprite = cc.PhysicsSprite.create(res.b_ball_01);
sprite.setBody( body );
return sprite;
}