2
我有一個小小的麻煩,因爲標題說:我無法弄清楚如何向槍指向的方向射擊子彈。Box2D - 從旋轉槍射擊子彈
這裏是短版的代碼,我的子彈發射:
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;
}
}
「'b2Vec2(cos(angle * PI/180),sin(angle))'」,是否是以弧度表示的角度? – genpfault
@genpfault:對於90度,我會把角度= 90.0f – Dant
我想我試圖指出,你沒有將'sin()'的參數轉換爲弧度,只有'cos()''秒。你需要做這兩件事,否則結果將是毫無意義的,或者至少是Funkytown的單程票。 – genpfault