2014-02-06 59 views
2

我有一種武器在擊中時會彈回下一個敵人。Box2d - 用速度和角度計算衝動的問題

我首先通過計算三角洲和獲取角度開始:

float deltaX = e->m_body->GetPosition().x - m_body->GetPosition().x; 
float deltaY = e->m_body->GetPosition().y - m_body->GetPosition().y; 

float angle = atan2((deltaY), deltaX) * 180/M_PI; 

然後我的角度轉換爲向量,並通過15乘以(彈丸的速度):

b2Vec2 vec = b2Vec2(cos(angle*M_PI/180),sin(angle*M_PI/180)); 
vec *= 15.0f; 

最後,我申請的衝動體:

m_body->ApplyLinearImpulse(vec, m_body->GetPosition()); 

的問題是,該載體畝由於子彈沒有朝着正確的方向行進,因此不正確。如果我只是將角度輸出給下一個敵人,它傾向於輸出一個看起來正確的角度,所以問題必須在轉換爲向量時出現。

回答

2

我不認爲你需要在這裏使用任何三角函數,因爲你已經有了方向:

b2Vec2 direction = e->m_body->GetPosition() - m_body->GetPosition(); 
direction.Normalize(); // this vector now has length 1 

float speed = ...; 
m_body->ApplyLinearImpulse(speed * direction, m_body->GetWorldCenter());