程序运行截图
程序实现的功能是在鼠标点击位置生成一个自由下落的小球并进行碰撞检测和碰撞处理。
在cocos2d-x中使用box2d的主要步骤
创建世界
b2Vec2 gravity;
gravity.Set( 0 .0f, - 10 .0f); world = new b2World(gravity); b2Body *groundBody = createGround( 0 , 0 , winSize.width, winSize.height); b2Body *HelloWorld::createGround( int sx, int sy, int width, int height) { b2BodyDef groundBodyDef; groundBodyDef.position.Set(sx, sy); b2Body *groundBody = world->CreateBody(&groundBodyDef); b2EdgeShape groundBox; //botttom groundBox.Set(b2Vec2( 0 , 0 ), b2Vec2(width / PTM_RATIO, 0 )); groundBody->CreateFixture(&groundBox, 0 ); // top groundBox.Set(b2Vec2( 0 , height / PTM_RATIO), b2Vec2(width / PTM_RATIO, height / PTM_RATIO)); groundBody->CreateFixture(&groundBox, 0 ); // left groundBox.Set(b2Vec2( 0 , height / PTM_RATIO), b2Vec2( 0 , 0 )); groundBody->CreateFixture(&groundBox, 0 ); // right groundBox.Set(b2Vec2(width / PTM_RATIO, height / PTM_RATIO), b2Vec2(width / PTM_RATIO, 0 )); groundBody->CreateFixture(&groundBox, 0 ); return groundBody; } |
创建物体
void
HelloWorld::createSprite(CCPoint location,
char
image[]) { CCSprite *sprite = CCSprite::create(image); this ->addChild(sprite); sprite->setPosition(location); b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(location.x / PTM_RATIO, location.y / PTM_RATIO); bodyDef.userData = sprite; b2Body *body = world->CreateBody(&bodyDef); b2CircleShape dynamicBox; dynamicBox.m_radius = 12 .0f / PTM_RATIO; b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1 .0f; fixtureDef.friction = 0 .3f; body->CreateFixture(&fixtureDef); } |
实现更新
void
HelloWorld::update(
float
dt) { int velocityIterations = 8 ; int positionIterations = 1 ; world->Step(dt, velocityIterations, positionIterations); for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() != NULL ) { CCSprite *mActor = (CCSprite *)b->GetUserData(); mActor->setPosition(ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO)); mActor->setRotation(- 1 * CC_RADIANS_TO_DEGREES(b->GetAngle())); //note } } } |
源代码下载