toge's diary

コンピュータ関連の趣味をつらつらと。

誘導弾のコードを弄ってみる

シューティングゲームアルゴリズムマニアックスの記事のまま実装してたけど、大分簡潔に書けるね。もうちょっと速くなるかな。
これならSSE化する価値あるかも。

Vector direct = player_position - bullet_position;

float direct_size = direct.size();
float bullet_size = bullet_speed.size();

// 内積を求め、一定角度内ならその速度に合わせる。
if (bullet_speed * direct > bullet_size * direct_size * cosf)
{
  bullet_speed = direct / direct_size * bullet_size;
}
// 一定角度以上なので、近い方の限界角度まで曲げる。
else
{
  float x = bullet_speed.x();
  float y = bullet_speed.y();

  if (direct * Vector(-y, x) >= 0)
    bullet_speed = Vector(cosf2 * x - sinf2 * y, cosf2 * y + sinf2 * x);
  else
    bullet_speed = Vector(cosf2 * x + sinf2 * y, cosf2 * y - sinf2 * x);
}