Unity3D 初涉门径 之鼠标控制视角转动

前面,学了物体的移动功能,现在来学一下鼠标控制摄像机(视角)移动 ( ⊙o⊙ )~。

代码如下:
C#脚本(在Unity 5.5.1 下能运行):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class MouseView : MonoBehaviour {

    public enum RotationAxes
    {
        MouseXAndY = 0,
        MouseX = 1,
        MouseY = 2
    }

    public RotationAxes m_axes = RotationAxes.MouseXAndY;
    public float m_sensitivityX = 10f;
    public float m_sensitivityY = 10f;

    // 水平方向的 镜头转向
    public float m_minimumX = -360f;
    public float m_maximumX = 360f;
    // 垂直方向的 镜头转向 (这里给个限度 最大仰角为45°)
    public float m_minimumY = -45f;
    public float m_maximumY = 45f;

    float m_rotationY = 0f;


    // Use this for initialization
    void Start () {
        // 防止 刚体影响 镜头旋转
        if (GetComponent()) {
            GetComponent ().freezeRotation = true;
        }
    }

    // Update is called once per frame
    void Update () {
        if (m_axes == RotationAxes.MouseXAndY) {
            float m_rotationX = transform.localEulerAngles.y + Input.GetAxis ("Mouse X") * m_sensitivityX;
            m_rotationY += Input.GetAxis ("Mouse Y") * m_sensitivityY;
            m_rotationY = Mathf.Clamp (m_rotationY, m_minimumY, m_maximumY);

            transform.localEulerAngles = new Vector3 (-m_rotationY, m_rotationX, 0);
        } else if (m_axes == RotationAxes.MouseX) {
            transform.Rotate (0, Input.GetAxis ("Mouse X") * m_sensitivityX, 0);
        } else {
            m_rotationY += Input.GetAxis ("Mouse Y") * m_sensitivityY;
            m_rotationY = Mathf.Clamp (m_rotationY, m_minimumY, m_maximumY);

            transform.localEulerAngles = new Vector3 (-m_rotationY, transform.localEulerAngles.y, 0);
        }
    }
}

调用时,只需把该脚本绑定给物体即可。这里是绑定摄像机,以摄像机为第一人称视角转动。

你可能感兴趣的:(Unity-3D)