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

cocos2dx自学之使用box2d物理世界

发布时间:2020-12-14 14:17:18 所属栏目:百科 来源:网络整理
导读:需要引入的头文件 #include "cocos2d.h" #include "Box2DBox2D.h" #include string 创建物理世界 world = new b2World(b2Vec2(0,-10)); 创建会自由掉落的 精灵 bird = Sprite::create("bird0_0.png");bird-setName("bird");Size size = bird-getContentSize

需要引入的头文件

#include "cocos2d.h"
#include "Box2DBox2D.h"
#include <string>


创建物理世界

world = new b2World(b2Vec2(0,-10));

创建会自由掉落的 精灵
bird = Sprite::create("bird0_0.png");
	bird->setName("bird");
	Size size = bird->getContentSize();
	b2BodyDef def;
	def.type = b2_dynamicBody;
	def.position = b2Vec2(screenSize.width / 4 / RATIO,screenSize.height / 2 / RATIO + 1);//鸟的位置
	b2PolygonShape shape;
	shape.SetAsBox(size.width/2/RATIO,size.height/2/RATIO); //碰撞体积?
	b2FixtureDef fixtureDef;
	fixtureDef.density = 1;
	fixtureDef.friction = 0.3;
	fixtureDef.shape = &shape;
	b2Body *body = world->CreateBody(&def);
	body->CreateFixture(&fixtureDef);
	addChild(bird);
	bird->setPosition(Point(def.position.x*RATIO,def.position.y*RATIO));//物理物体会自动往下掉 因此绑定物理物体的位置到sprite上 就形成了物理
	body->SetUserData(bird);//与sprite绑定
	this->body = body;


必须将精灵与物理盒子绑定才能实现物理效果 此方法必须每秒执行,不停的将精灵与物理盒子位置绑定
void HelloWorld::bingSprite(){ //让物理盒子和精灵实时绑定来达到物理效果 物理盒子本身是看不到的
	Sprite *s;
	for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()){
		s = (Sprite*)b->GetUserData();
		if (b->GetUserData() && b->GetType() == b2_dynamicBody||b->GetType()==b2_kinematicBody){
			if (s != NULL){
				s->setPosition(b->GetPosition().x*RATIO,b->GetPosition().y*RATIO);//每次渲染都让sprite与box body保持位置绑定
			}
			
		}
	}
}



添加道路物体 精灵下落时会落在上面
Sprite *ground = Sprite::create("land.png");
	Size size = ground->getContentSize();
	ground->setScaleX(2);
	ground->setScaleY(2);
	b2BodyDef bDef;
	bDef.type = b2_staticBody;
	bDef.position = b2Vec2(size.width/2/RATIO,size.height/2/RATIO);//设置碰撞物体的位置
	b2PolygonShape groundShape;
	groundShape.SetAsBox(size.width/2/RATIO,size.height/2/RATIO-0.3);//position 和SetAsBox 都可以改变碰撞物体的位置 不知为何
	b2Body *groundBody = world->CreateBody(&bDef);
	b2FixtureDef fix;
	fix.shape = &groundShape;
	groundBody->CreateFixture(&fix);
	groundBody->SetUserData(ground);
	addChild(ground);

linearVelocity 是设置盒子执行的动作 如 往各个方向移动


物理盒子有 三种类型 漂浮物体 静态物体 和动态物体

漂浮物体不受重力音响 可自由移动,静态物体位置是固定的不会掉落, 动态物体会自由掉落


笔记至此结束

(编辑:李大同)

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

    推荐文章
      热点阅读