1
2

More than 3 years have passed since last update.

FPSのカメラを作る

Last updated at Posted at 2021-02-09

マウスでFPSの用にカメラを動かすという仕組みを作ることがあると思います。
その場合、こんなコードを書きがちではないでしょうか。

// 誤ったコード
void Update(){
    float sensitivity = 2;

    float yaw = Input.GetAxis("Mouse X") * sensitivity;
    float pitch = -Input.GetAxis("Mouse Y") * sensitivity;
    transform.rotation = transform.rotation Quaternion.Euler(pitch, yaw, 0);
}

ところが、マウスを回すように動かすとこのように水平線が傾いてしまいます。

screen.png

なぜかというと、ピッチ(上下の首振り)とヨー(左右の首振り)は順序が違うためです。
結論から言えば、以下のコードを書けば、水平線が傾くことはありません。

void Update(){
    float sensitivity = 2;

    float yaw = Input.GetAxis("Mouse X") * sensitivity;
    float pitch = -Input.GetAxis("Mouse Y") * sensitivity;
    transform.rotation = Quaternion.Euler(0, yaw, 0) * transform.rotation * Quaternion.Euler(pitch, 0, 0);
}

なお、これだとマウスを上に動かし続けるとそのうち逆さになります。
ということで、ピッチに上限下限を付けて一定以上首を振れないようにしましょう。

真上を0度として90度なら水平、180度なら真下を向くとして計算するといいです。

    var forward = transform.rotation * Vector3.forward;
    var angle = Vector3.Angle(forward, Vector3.up);

    if (angle + pitch < 10f) { pitch = 10f - angle; }
    if (170f < angle + pitch) { pitch = 170f - angle; }
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2