代码之家  ›  专栏  ›  技术社区  ›  Frank

如何在box2d体中设置精灵的位置?

  •  1
  • Frank  · 技术社区  · 16 年前

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

    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);
    
    2 回复  |  直到 16 年前
        1
  •  2
  •   Staffan E    16 年前

    我所看到的只是,你在主体的用户数据中存储了一个指向sprite对象的指针,然后把它放在那里。如果你想把身体的位置转移到精灵身上,你需要每帧更新一次。

    在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
  •  0
  •   Singhak    12 年前

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

    在你的更新方法中

    就像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));