实现摄像机跟随
首先在unity的Hierarchy面板创建一个3D Object的Capsule,命名为Player。
把Main Camera重命名为Gun camera并作为Player的子物体
在Main Camera中添加c#脚本命名为mouselook
接下来编辑mouselook脚本实现以下功能:
1.摄像机的旋转
2.玩家左右旋转控制左右旋转
3.摄像机上下旋转控制上下旋转
public float mouseSensitivity = 100f;//视线灵敏度
public Transform playerBody;//玩家位置
public float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
//隐藏光标并锁定在窗口的中心
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X")* mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
//Debug.Log("mouseX:" + mouseX);
//Debug.Log("mouseY:" + mouseY);
xRotation -= mouseY;//上下旋转的轴值进行累计
xRotation = Mathf.Clamp(xRotation, -80f, 80f);//限制轴值的累计即上下看的角度
transform.localRotation = Quaternion.Euler(xRotation,0f,0f);
playerBody.Rotate(Vector3.up* mouseX);//玩家横向旋转
}
编写完脚本后
在Inspector面板给Player Body赋值:
即用鼠标把Hierarchy面板中的Player拖到Inspector面板中的Player Body