COCOS-HTML5-3.9版本学习四chipmunk物理引擎的测试

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

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...