加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 16:49:58 所属栏目:百科 来源:网络整理
导读: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()

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读