Box2D - 从旋转枪中射击子弹

时间:2017-08-11 17:32:56

标签: c++ visual-studio box2d

我有点麻烦,因为标题说:我无法弄清楚如何向枪指向的方向射击子弹。

Picture of problem

这是我的子弹射击的简短版本代码:

b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.bullet = true;
bd.position = gun->GetPosition();//bullet start at the middle of the gun
m_bullet = m_world->CreateBody(&bd);
m_bullet->CreateFixture(&fd);           
m_bullet->ApplyLinearImpulseToCenter( ??? ,true);

起初我认为第一个参数是你希望身体前进的方向,所以我放入gun->GetWorldPoint(b2Vec2(0.0f,-5.0f))(枪口中间)。大错过!过了一会儿,我想我应该尝试放入当前枪的旋转度b2Vec2 vect = b2Vec2(cos(angle * PI/180), sin(angle * PI/180));的向量,但子弹根本不会飞。现在我完全没有想法。请稍微说清楚。

完整版代码:

public:
b2Body* m_bullet = NULL;
b2Body* gun;
b2RevoluteJoint* joint1;
b2FixtureDef fd;

TestingStuff()
{
    {
        //body
        b2CircleShape circle1;
        circle1.m_radius = 1.6f;

        fd.shape = &circle1;
        fd.density = 1.0f;
        fd.filter.groupIndex = -1;          

        b2BodyDef bd1;
        bd1.type = b2_staticBody;
        bd1.position.Set(-5.0f, 9.0f);
        b2Body* body1 = m_world->CreateBody(&bd1);
        body1->CreateFixture(&fd);

        //gun
        b2PolygonShape box;
        box.SetAsBox(0.5f, 5.0f);

        fd.shape = &box;
        fd.density = 1.0f;
        fd.filter.groupIndex = -1;

        b2BodyDef bd2;
        bd2.type = b2_dynamicBody;
        bd2.position.Set(-5.0f, 8.0f);
        gun = m_world->CreateBody(&bd2);
        gun->CreateFixture(&fd);

        //joint
        b2RevoluteJointDef jd1;
        jd1.Initialize(gun, body1, bd1.position);
        jd1.enableMotor = true;
        jd1.maxMotorTorque = 90;
        jd1.motorSpeed = 180 * DEGTORAD;//DEGTORAD=0.0174532925199432957f
        joint1 = (b2RevoluteJoint*) m_world->CreateJoint(&jd1);
    }

}

void Keyboard(int key)
{
    switch (key)
    {
    case GLFW_KEY_COMMA:
        if (m_bullet != NULL)
        {
            m_world->DestroyBody(m_bullet);
            m_bullet = NULL;
        }

        {
            //bullet
            b2CircleShape shape;
            shape.m_radius = 0.25f;

            fd.shape = &shape;
            fd.density = 1;
            fd.restitution = 0.05f;
            fd.filter.groupIndex = -1;

            b2BodyDef bd;
            bd.type = b2_dynamicBody;
            bd.bullet = true;
            bd.position = gun->GetPosition();
            m_bullet = m_world->CreateBody(&bd);
            m_bullet->CreateFixture(&fd); 
            m_bullet->ApplyLinearImpulseToCenter( ??? ,true);
        }
        break;
    }
}

0 个答案:

没有答案