cocos2d-x Box2D入门示例

程序运行截图

程序实现的功能是在鼠标点击位置生成一个自由下落的小球并进行碰撞检测和碰撞处理。

在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
        }
    }
}

源代码下载

点击打开链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值