【问题标题】:How to set the position of a sprite within a box2d body?如何在 box2d 体内设置精灵的位置?
【发布时间】:2010-02-25 19:10:59
【问题描述】:

基本上我的身体有 2 个多边形。当我为 userData 添加精灵时,纹理的位置不是我想要的。我想要做的是调整纹理在体内的位置。这是我设置的代码示例:

CCSpriteSheet *sheet = (CCSpriteSheet*) [self getChildByTag:kTagSpriteSheet];
CCSprite *pigeonSprite = [CCSprite spriteWithSpriteSheet:sheet rect:CGRectMake(0,0,40,32)];
[sheet addChild:pigeonSprite z:0 tag:kPigeonSprite];

pigeonSprite.position = ccp( p.x, p.y);

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape dynamicCircle;
dynamicCircle.m_radius = .25f;
dynamicCircle.m_p.Set(0.0f, 1.0f);

        // Define the dynamic body fixture.
b2FixtureDef circleDef;
circleDef.shape = &dynamicCircle;   
circleDef.density = 1.0f;
circleDef.friction = 0.3f;

body->CreateFixture(&circleDef);

b2Vec2 vertices[3];
vertices[0].Set(-0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f);
vertices[2].Set(0.0f, 1.0f);
b2PolygonShape triangle;
triangle.Set(vertices, 3);

b2FixtureDef triangleDef1;
triangleDef1.shape = ▵ 
triangleDef1.density = 1.0f;
triangleDef1.friction = 0.3f;

body->CreateFixture(&triangleDef1);

【问题讨论】:

  • 我可以建议尝试从代码 sn-p 中删除所有不必要的内容吗?例如,密度和摩擦力几乎与精灵定位无关。一方面,我不愿意通过一大段代码来回答一个简单的问题。另一方面,如果您不确定某件事是否不会影响您的问题,最好将其保留。但请尽量减少到最低限度。

标签: iphone cocos2d-iphone box2d box2d-iphone


【解决方案1】:

我对objective-c不太熟悉,但我会尝试一下。

我所看到的是,您将指向精灵对象的指针存储在主体的用户数据中,然后将其留在那里。如果您希望将身体的位置转移到精灵,您需要每帧更新它。

在 C++ 中,这看起来像这样。

// To be called each time physics should be updated.
void physicsStep(float32 timeStep, int32 velocityIterations, int32 positionIterations) {
    // This is the usual update routine.
    world.Step(timeStep, velocityIterations, positionIterations);
    world.ClearForces();

    // SpriteClass can be replaced with any class you favor.
    // Assume there is a known pointer to the b2Body. Otherwise you'll have to get that,
    // or iterate over all bodies in the world.
    SpriteClass *sprite = (SpriteClass*)body->GetUserData();

    // Once you have the pointer you can transfer all the data.
    sprite.position = body->GetPosition();
    sprite.angle = body->GetAngle();
    // ... and so on
}

用户数据只是 b2Body 中的任意存储空间,Box2D 不知道您决定在其中存储什么。

【讨论】:

    【解决方案2】:

    要使用身体移动精灵,那么你必须根据身体设置精灵位置

    在您的更新方法中

    像这样在 COCOS2D-X 这里

    sprite = static_cast<CCSprite*>body->GetUserData();
    sprite->setPosition(vec2(body->GetPosition().x*PTM_RATIO, body->GetPosition().y*PTM_RATIO));
    sprite->setRotation(-CC_Radian_to_Degree(body->GetAngle));
    

    PTM_RATIO = 32;

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多