CCSprite在COCOS2dx中不充当物理主体?

时间:2014-03-12 16:53:54

标签: c++ sprite cocos2d-x game-physics ccsprite

我有以下函数初始化cocos2dx中的场景,据我所知,我已经做好了一切。但是我的CCSprite仍然没有充当物理学的身体。它在屏幕中央保持静止,但它应该下降并受到重力的影响。

任何帮助将不胜感激。提前谢谢。

void HelloWorld::initPhysics()
{
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
//creating the world
b2Vec2 gravity;
gravity.Set(0.0f, -20.0f);
world = new b2World(gravity);

// Do we want to let bodies sleep?
world->SetAllowSleeping(true);

world->SetContinuousPhysics(true);


CCSprite* bird = CCSprite::create("Harry@2x.png");
bird->setScale(2.0);
bird->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
addChild(bird);

b2Body *_body;
// Create ball body and shape
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(screenSize.width,screenSize.height);
ballBodyDef.userData = bird;
_body = world->CreateBody(&ballBodyDef);

b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;

b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 100.0f;
ballShapeDef.friction = 0.5f;
ballShapeDef.restitution = 0.7f;
_body->CreateFixture(&ballShapeDef);
}

这是我的更新功能,我已将世界变量添加为全局。

void HelloWorld::update(float dt)
{
int velocityIterations = 8;
int positionIterations = 1;

world->Step(dt, velocityIterations, positionIterations);

//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
    if (b->GetUserData() != NULL) {
        //Synchronize the AtlasSprites position and rotation with the corresponding body
        CCSprite* myActor = (CCSprite*)b->GetUserData();
        myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
        myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
    }
}
}

1 个答案:

答案 0 :(得分:3)

您的b2World* world是一个局部变量。这意味着它将超出当前函数末尾的范围,这表示您无法调用world->Step(..)方法,这是您必须定期调用的方法(通常每帧)为了推进物理世界的发展。如果不走向世界,就不会有任何动静。