在很多的游戏中我们都看到第一人称视角,下面是第一人称视角的创建
首先先新建一个场景,然后添加一个胶囊体,把摄像机放到胶囊体上调整位置并且把摄像机设置为胶囊体的子对象
新建C#脚本
命名为MouseLook.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public enum RotationAxex
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public RotationAxex axes = RotationAxex.MouseXAndY;
//旋转速度
public float sensitiveityHor = 9.0f;
public float sensitiveityVert = 9.0f;
//垂直旋转最大和最小值
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
//垂直角度
private float _rotationX = 0;
// Use this for initialization
void Start()
{
Rigidbody body = GetComponent<Rigidbody>();
if (body != null)
{
body.freezeRotation = true;
}
}
// Update is called once per frame
void Update()
{
if (axes == RotationAxex.MouseX)
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitiveityHor, 0);
else if (axes == RotationAxex.MouseY)
{
//基于鼠标增加垂直角度
_rotationX -= Input.GetAxis("Mouse Y") * sensitiveityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
//保持Y的角度一样
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
else
{
_rotationX -= Input.GetAxis("Mouse Y") * sensitiveityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
//旋转变化量
float delta = Input.GetAxis("Mouse X") * sensitiveityHor;
//使用delta递增旋转角度
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}
Mathf.Clamp用于限制视角查看范围,限制_rotationX的值在minimumVert和maximumVert之间返回
在摄像机和胶囊体上分别挂上MouseLook脚本
选中摄像机,在Inspector面板上的MouseLook脚本上设置Axes值为Mouse Y
选中胶囊体,设置MouseLook脚本的Axes值为Mouse X
这么一来第一人称视角观察就完成了