box2d之刚体,定制器笔记

时间:2022-09-01 18:36:43

刚体(Body):
通过世界创建的对象,物理引擎里面所有东西都是刚体
创建方式:
定义一个b2BodyDef,b2World调用createBody的方法传入此参数

定制器(Fixture):
带有形状,密度,摩擦力等属性
创建方式:
定义一个b2FixtureDef,调用刚体的createFixture方法为刚体创建定制器(相当于附加属性),每个刚体支持添加多个Fixture;
刚体的createFixture重载了两种模式,一种是b2FixtureDef作为参数,一种是shape作为参数,效果是一样的。

形状(shape):
刚体的形状
种类:
circle(圆形),Polygon(多边形),其他等等

基本上他们的范围是这样:world,body,fixture(刚体的多个属性)


tips:b2Vec2是2dx里面类似CGPoint的东西

 

具体看代码

box2d之刚体,定制器笔记
 1     //刚体
2 b2BodyDef testBodyDef;
3 testBodyDef.type = b2_staticBody;
4 testBodyDef.position.Set(0,0);
5
6 //底部的边缘线
7 b2EdgeShape testShape;
8 testShape.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
9
10 b2FixtureDef testFixtueDef;
11 testFixtueDef.shape = &testShape;
12
13 b2Body* testBody = world->CreateBody(&testBodyDef);
14 testBody->CreateFixture(&testFixtueDef);
15
16 //顶部边缘线
17 testShape.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
18 testBody->CreateFixture(&testFixtueDef);
19
20 //左边边缘线
21 testShape.Set(b2Vec2(0,0), b2Vec2(0,s.height/PTM_RATIO));
22 testBody->CreateFixture(&testFixtueDef);
23
24 //右边边缘线
25 testShape.Set(b2Vec2(s.width/PTM_RATIO,0), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
26 testBody->CreateFixture(&testFixtueDef);
27
28 //创建可运动的缸体
29 CCPoint ballPosition = CCPointMake(200, 100);
30 CCSprite* ballSprite = CCSprite::create("Ball.png");
31 ballSprite->setPosition(ballPosition);
32 this->addChild(ballSprite);
33
34 b2BodyDef moveableBodyDef;
35 moveableBodyDef.type = b2_dynamicBody;
36
37 //设置刚体位置
38 //刚体相对于世界的位置,坐标转换为box2d里面的坐标
39 moveableBodyDef.position.Set(ballPosition.x/PTM_RATIO,ballPosition.y/PTM_RATIO);
40 //把精灵放到b2BodyDef的userData里面,在update里面刷新精灵位置
41 moveableBodyDef.userData = ballSprite;
42
43 b2Body *moveableBody = world->CreateBody(&moveableBodyDef);
44
45 //创建圆形小球
46 b2CircleShape testCircleShape;
47 //刚体和形状设置坐标的时候,选一个就ok
48 testCircleShape.m_p.Set(0,0);
49 float radius = ballSprite->getContentSize().width/(2*PTM_RATIO);
50 testCircleShape.m_radius = radius;
51
52 b2FixtureDef moveableFixtureDef;
53 moveableFixtureDef.shape = &testCircleShape;
54 moveableFixtureDef.density = 1.0f;
55 moveableFixtureDef.friction = 0.3f;
56 moveableBody->CreateFixture(&moveableFixtureDef);
box2d之刚体,定制器笔记

update方法

box2d之刚体,定制器笔记
 1 void HelloWorld::update(float dt)
2 {
3 int velocityIterations = 8;
4 int positionIterations = 1;
5
6 world->Step(dt, velocityIterations, positionIterations);
7
8 //刷新精灵位置
9 for (b2Body* body = world->GetBodyList(); NULL!= body; body = body->GetNext())
10 {
11 if ( NULL != body->GetUserData() )
12 {
13 CCSprite* sprite = (CCSprite*)body->GetUserData();
14
15 sprite->setPosition( CCPointMake( body->GetPosition().x * PTM_RATIO, body->GetPosition().y * PTM_RATIO) );
16 sprite->setRotation( -1 * CC_RADIANS_TO_DEGREES(body->GetAngle()) );
17 }
18 }
19 }