0
Ch.2中的SFML遊戲開發書。圖4給出了當你通過兩個方向(例如右和上)增加速度時,那麼運動將比在一個方向上更快。Hallet 2D對角線運動的SFML遊戲開發書
從研究中,我瞭解到,觀察到的行爲是,您將在同一時間段內達到對角線距離,就像您向左或向右或向上或向下移動一樣。這是錯誤的,因爲對角距離更長。
該書由SQRT除以2糾正此問題:
sf::Vector2f velocity = mPlayerAircraft->getVelocity();
// If moving diagonally, reduce velocity (to have always same velocity)
if (velocity.x != 0.f && velocity.y != 0.f)
mPlayerAircraft->setVelocity(velocity/std::sqrt(2.f));
從額外的研究,我發現,所述溶液可通過將速度的歸一化矢量的速度相乘來實現。
velocity = mPlayerAircraft->getVelocity();
if (velocity.x != 0.f && velocity.y != 0.f) {
float velocityxsq = velocity.x * velocity.x;
float velocityysq = velocity.y * velocity.y;
float magnitude = std::sqrt(velocityxsq + velocityysq);
sf::Vector2f normalizedVector = velocity/magnitude;
velocity.x = velocity.x * std::abs(normalizedVector.x);
velocity.y = velocity.y * std::abs(normalizedVector.y);
mPlayerAircraft->setVelocity(velocity);
}
行爲似乎是由兩種實現,但歸一化值正確並不總是1/SQRT(2)。唯一一次計算結果相同的情況是遊戲開始時,我開始做對角線運動。如果我移動任何方向然後進行對角線移動,則數值會有所不同。
我做了規範化不正確嗎? 爲什麼本書靜態使用sqrt(2)?
太棒了,謝謝! –