box2d-基本概念
世界:
创建世界对象作为一切对象的父对象;
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f); //重力大小;
bool doSleep = false; //静止位置不在进行物理模拟;
world = new b2World(gravity, doSleep);
world->SetContinuousPhysics(true);
tick函数中;进行物理模拟:
int32 velocityIterations = 8; //速度迭代次数;
int32 positionIterations = 1; //位置迭代次数;
world->Step(dt, velocityIterations, positionIterations); //dt 是模拟的间隔时间;
遍历world中的body(刚体):
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
遍历world中的碰撞点:
for (b2Contact* c = myWorld->GetContactList(); c; c = c->GetNext())
遍历world中的全部关节:
for (b2Joint* j = myWorld->GetJointList(); j; j = j->GetNext())
找到所需的刚体或者碰撞点或是关节,都不能直接删除对象;缓存后在后边删除;
例如我们需要删除pos刚体:
b2Body *body = *pos;
world->DestroyBody(body);
物体对象(刚体):b2BOdy
(1)类型:
armBodyDef.type = b2_dynamicBody; //动态刚体
armBodyDef.type = b2_staticBody; //静态刚体;(大地,墙壁等)
armBodyDef.type = b2_kinematicBody; //平面刚体,(按固定路线运动的刚体)
(2)位置:
armBodyDef.position.Set(230.0/PTM_RATIO, (FLOOR_HEIGTH+91.0)/PTM_RATIO);
(3)是否旋转:
armBodyDef.fixedRotation= true; //物体发生碰撞时,不发生旋转;
(4)物理世界的刚体和图形精灵进行映射;通过物理世界的刚体变化,然后再tick函数中改变图形精灵的状态;达到模拟物理世界的效果;
bodyDefC.userData = spriteC;
(5)其他:
armBodyDef.linearDamping = 1; //线性运动;
armBodyDef.angularDamping = 1; //阻尼系数;
armBodyDef.angle = 30.0; //角度;
armBodyDef.bullet = YES; //设为yes;告诉物理世界,这是个高速运动的物体,需要小心的进行物理模拟;
Fixture(夹具):
(1)形状:
b2PolygonShape dynamicBox0;
dynamicBox0.SetAsBox(.5f, .5f);
b2FixtureDef fixtureDef0;
fixtureDef0.shape = &dynamicBox0;
(2)其他:
b2FixtureDef fixtureDef0; fixtureDef0.shape = &dynamicBox0; //形状;
fixtureDef0.density = 1.0f; //密度; fixtureDef0.friction = 0.3f; //摩擦力; fixtureDef0.restitution = 0.4;//回复力(弹力) fixtureDef0.isSensor = true; //任何物体与之发生碰撞都不会有碰撞效果;