具有角色移动、视角、重力和跳跃的完整PlayerController代码。
public class PlayerController : MonoBehaviour
{
[Header("Unity组件")]
public CharacterController m_Controller;
public Transform playerCamera;
[Header("玩家数值")]
public float moveSpeed = 6.0F;
public float mouseSensitivity = 1000.0F;
public float playerGravity = 9.8F;
public float jumpHeight = 2F;
public float verticalVelocity = 0;// 垂直速度
private float x_RotationOffset = 0;// 累计x旋转
private float y_RotationOffset = 0;// 累计y旋转
void Start()
{
m_Controller = this.GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;// 鼠标锁定
}
private void FixedUpdate()
{
PlayerRotation();
PlayerMovement();
}
// 控制角色移动
public void PlayerMovement()
{
Vector3 moveDirection = Vector3.zero;
// 获取键盘输入:Horizontal左右移动;Vertical前后移动
// 加入自身tranform方向
moveDirection = Vector3.zero;
moveDirection += transform.forward * Input.GetAxis("Vertical");
moveDirection += transform.right * Input.GetAxis("Horizontal");
moveDirection *= Time.fixedDeltaTime * moveSpeed;
// 重力
if (!m_Controller.isGrounded)
verticalVelocity -= playerGravity * Time.fixedDeltaTime;// a*t=v
else
verticalVelocity = 0.0F;
// 跳跃
if (Input.GetButton("Jump"))
{
// 得在地面才能跳
if (m_Controller.isGrounded)
{
verticalVelocity = Mathf.Sqrt(jumpHeight * 2 / playerGravity) * playerGravity;// 初始向上速度
}
}
moveDirection.y += verticalVelocity * Time.fixedDeltaTime;// v*t=s
// 移动
m_Controller.Move(moveDirection);
}
// 控制角色视角
private void PlayerRotation()
{
// 获取鼠标移动
x_RotationOffset += Input.GetAxis("Mouse X")* Time.fixedDeltaTime * mouseSensitivity;// 水平方向
y_RotationOffset += Input.GetAxis("Mouse Y")* Time.fixedDeltaTime * mouseSensitivity;// 垂直方向
// 限制垂直旋转角度
y_RotationOffset = Mathf.Clamp(y_RotationOffset, -45f, 45f);
// 旋转
transform.rotation = Quaternion.Euler(new Vector3(0, x_RotationOffset, 0));// Player旋转
playerCamera.localRotation= Quaternion.Euler(new Vector3(y_RotationOffset, playerCamera.localEulerAngles.y, playerCamera.localEulerAngles.z));// Camera旋转
}
}