【问题标题】:In Box2D, how to fix body's rotation在 Box2D 中,如何固定身体的旋转
【发布时间】:2018-10-15 00:58:33
【问题描述】:

我正在使用 cocos2d-x 的 box2d。

像这张图片,我的char有盒子状的身体,

我的字符在被击中时会旋转。

但我希望我的 char 的身体不旋转。

我知道精灵是如何不旋转的。

但我不知道如何修复身体的旋转。


myChar 的代码

    void HelloWorld::makeMe()
    {   
        Sprite* pSprite = Sprite::create("shipBeige_manned.png");
        pSprite->setPosition(Vec2(100,100));
        this->addChild(pSprite);    
        b2BodyDef bodyDef;
        bodyDef.type = b2_dynamicBody;
        bodyDef.position.Set(100 / PTM_RATIO, 100 / PTM_RATIO);
        bodyDef.userData = pSprite;

        b2Body* body = _world->CreateBody(&bodyDef);

        b2PolygonShape pho;
        pho.SetAsBox(1.24f, 1.22f); 

        b2FixtureDef fixtureDef;

        fixtureDef.shape = &pho;

        fixtureDef.density = 1.0f;

        fixtureDef.friction = 0.2f;

        fixtureDef.restitution = 0.0f;
        body->CreateFixture(&fixtureDef);


        pSprite->setName("me");
    }

更新(勾选)代码

    void HelloWorld::tick(float dt)
    {   


        int velocityIterations = 8;
        int positionIterations = 3;

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


        for (b2Body* b = _world->GetBodyList(); b; b = b->GetNext())
        {
            if (b->GetUserData() != nullptr) {
                Sprite* spriteData = (Sprite *)b->GetUserData();
                spriteData->setPosition(Vec2(b->GetPosition().x * PTM_RATIO,
                    b->GetPosition().y * PTM_RATIO));
                spriteData->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));
            }
        }
    }

【问题讨论】:

    标签: c++ cocos2d-x box2d


    【解决方案1】:

    我在 Char 的身体上使用 SetFixedRotation。

        void HelloWorld::makeMe()
        {   
            Sprite* pSprite = Sprite::create("shipBeige_manned.png");
            pSprite->setPosition(Vec2(100,100));
            this->addChild(pSprite);    
            b2BodyDef bodyDef;
            bodyDef.type = b2_dynamicBody;
            bodyDef.position.Set(100 / PTM_RATIO, 100 / PTM_RATIO);
            bodyDef.userData = pSprite;
    
            b2Body* body = _world->CreateBody(&bodyDef);
            body->SetFixedRotation(true);  <----add this code
            b2PolygonShape pho;
            pho.SetAsBox(1.24f, 1.22f); 
    
            b2FixtureDef fixtureDef;
    
            fixtureDef.shape = &pho;
                // 밀도
            fixtureDef.density = 1.0f;
            // 마찰력 - 0 ~ 1
            fixtureDef.friction = 0.2f;
            // 반발력 - 물체가 다른 물체에 닿았을때 팅기는 값
            fixtureDef.restitution = 0.0f;
            body->CreateFixture(&fixtureDef);
    
    
            pSprite->setName("me");
        }
    

    【讨论】:

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