【问题标题】:CCSprite not acting as Physics body in COCOS2dx?CCSprite 不充当 COCOS2dx 中的物理体?
【发布时间】:2014-04-17 00:00:24
【问题描述】:

我有以下函数初始化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()) );
    }
}
}

【问题讨论】:

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


    【解决方案1】:

    您的b2World* world 是一个局部变量。这意味着它将在当前函数结束时超出范围,这表明您无法调用 world->Step(..) 方法,这是您必须定期调用的方法(通常是每一帧)以推进物理世界的状态。不踏入世界就没有动静。

    【讨论】:

    • 我在问题中添加了我的更新功能,还添加了b2world world 作为我的全局变量。但仍然无法让CCSprite 回复物理?有什么帮助吗?
    • 对不起!!忘记调用scheduleUpdate(); 函数!物理工作甜蜜! :) 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多