创建一个unity 第一人称脚本
时间: 2023-09-23 20:02:29 浏览: 131
以下是一个示例的Unity第一人称脚本:
```
using UnityEngine;
public class FirstPersonController : MonoBehaviour
{
public float speed = 5.0f;
public float sensitivity = 2.0f;
private CharacterController controller;
private Camera camera;
private float verticalRotation = 0.0f;
void Start()
{
controller = GetComponent<CharacterController>();
camera = GetComponentInChildren<Camera>();
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * speed;
float vertical = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(horizontal, 0, vertical);
movement = transform.rotation * movement;
controller.Move(movement * Time.deltaTime);
float mouseHorizontal = Input.GetAxis("Mouse X") * sensitivity;
float mouseVertical = Input.GetAxis("Mouse Y") * sensitivity;
transform.Rotate(0, mouseHorizontal, 0);
verticalRotation -= mouseVertical;
verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
camera.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
if (Input.GetKeyDown(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
}
else if (Cursor.lockState == CursorLockMode.None && Input.GetMouseButton(0))
{
Cursor.lockState = CursorLockMode.Locked;
}
}
}
```
该脚本包括以下功能:
- 按WSAD键移动角色
- 使用鼠标控制视角旋转
- 限制视角旋转角度
- 按Esc键解锁光标
- 按左键锁定光标
阅读全文