Help us understand the problem. What is going on with this article?

一人称視点のカメラをマウスで操作できるように(Unity)

自分用のメモです。

Quaternionを使わないやり方で書いてます。
このスクリプトをPlayerプレハブのルートオブジェクトに追加すればOK。
垂直方向の回転に制限をかけるのが意外と面倒でした。

PlayerViewControl.cs
using UnityEngine;

public class PlayerViewControl : MonoBehaviour
{
    const int ROTATE_MOUSE_BUTTON = 0;

    const float MaxAngleX = 60f;
    const float MinAngleX = -60f;

    const float RotateSpeedH = 100.0f;
    const float RotateSpeedV = 70.0f;

    [SerializeField]
    Transform _playerCamera = null;

    Vector2 _prevMousePos;

    void Start()
    {
        _prevMousePos = Input.mousePosition;
    }

    void Update()
    {
        if (Input.GetMouseButton(ROTATE_MOUSE_BUTTON))
        {
            Vector2 mousePos = Input.mousePosition;

            if (mousePos == _prevMousePos) return;

            float angleH = (_prevMousePos.x - mousePos.x) / Screen.width * RotateSpeedH;
            float angleV = (mousePos.y - _prevMousePos.y) / Screen.height * RotateSpeedV;

            transform.localEulerAngles = RotateH(transform.localEulerAngles, angleH);
            _playerCamera.localEulerAngles = RotateV(_playerCamera.localEulerAngles, angleV);
        }

        _prevMousePos = Input.mousePosition;
    }

    Vector3 RotateH(Vector3 eulerAngles, float angle)
    {
        eulerAngles.y += angle;
        return eulerAngles;
    }

    Vector3 RotateV(Vector3 eulerAngles, float angle)
    {
        if (eulerAngles.x > 180f) eulerAngles.x -= 360f;
        eulerAngles.x = Mathf.Clamp(eulerAngles.x + angle, MinAngleX, MaxAngleX);
        if (eulerAngles.x < 0f) eulerAngles.x += 360f;
        return eulerAngles;
    }
}

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした