سؤال

I have the following function which initialises the scene in cocos2dxand to my knowledge i have done everything right. But my CCSprite is still not acting as a Physics body. It remains stationary in the centre of the screen whereas it should fall down and be affected by gravity.

Any help would be appreciated. Thanks in advance.

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);
}

Here is my update function and i have added the world variable as global.

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()) );
    }
}
}
هل كانت مفيدة؟

المحلول

Your b2World* world is a local variable. That means it'll be out of scope at the end of the current function, which indicates that you have no way of calling the world->Step(..) method which is the method you have to call regularly (every frame usually) in order to advance the physics world's state. Without stepping the world there will be no movement.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top