在Unity2019中做项目时,发现其中没有自带的第一人称控制器,于是我在网上参考多种教程,最终做出第一人称控制器,下面分享给大家。
新建一个空物体,重命名为 Player,并为其添加组件 Character Controller。将场景中的相机拖到 Player 下面,在 Player 下面放一个立方体,以便于观察。
在 Player 下面创建一个空物体,重命名为 GroundCheck,这个空物体用于检查人物是否与地面接触,以实现按下空格键产生弹跳效果。
为 Player 创建一个脚本 FirstPersonController。
using UnityEngine;
public class FirstPersonController : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 _velocity;
bool _isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
_isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance,
groundMask);
if (_isGrounded && _velocity.y < 0)
{
_velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && _isGrounded)
{
_velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
_velocity.y += gravity * Time.deltaTime;controller.Move(_velocity * Time.deltaTime);
}
}
为地形添加一个层 Ground。
FirstPersonController 脚本具体界面如下,Ground Mask 选择刚刚创建的 Ground 层,将 Player 身上的角色控制器 Character Controller 拖到 Controller 处。
为 Player 身上的相机创建脚本 MouseLook。
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
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;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
将 Player 拖到 Player Body 处。
至此第一人称控制器已完成制作。