成品展示
PlayerInput.cs
’‘’
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
[SerializeField]
private float speed = 5f; //移动速度大小
[SerializeField]
private float lookSensitivity = 8f; //视角转动速度大小
[SerializeField]
private PlayerController controller;
void Start()
{
Cursor.lockState = CursorLockMode.Locked; //隐藏鼠标
}
void Update()
{
float xMov = Input.GetAxisRaw("Horizontal"); //左右移动
float yMov = Input.GetAxisRaw("Vertical"); //前后移动
Vector3 velocity = (transform.right * xMov + transform.forward * yMov).normalized * speed;
controller.Move(velocity);
float xMouse = Input.GetAxisRaw("Mouse X"); //视角左右转动
float yMouse = Input.GetAxisRaw("Mouse Y"); //视角上下转动
Vector3 yRotation = new Vector3(0f, xMouse, 0f) * lookSensitivity;
Vector3 xRotation = new Vector3(-yMouse, 0f, 0f) * lookSensitivity;
controller.Rotate(yRotation, xRotation);
}
}
’‘’
PlayerController.cs
’‘’
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private Rigidbody rb;
[SerializeField]
private Camera cam; //视角
private Vector3 velocity = Vector3.zero; //速度:每秒移动的距离
private Vector3 yRotation = Vector3.zero; //旋转角色
private Vector3 xRotation = Vector3.zero; //选抓视角
public void Move(Vector3 _velocity)
{
velocity = _velocity;
}
public void Rotate(Vector3 _yRotation, Vector3 _xRotation)
{
yRotation = _yRotation;
xRotation = _xRotation;
}
private void PerformMovement() //移动位置
{
if(velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime); //计算移动位置
}
}
public void PerformRotation() //视角
{
if(yRotation != Vector3.zero)
{
rb.transform.Rotate(yRotation);
}
if(xRotation != Vector3.zero)
{
cam.transform.Rotate(xRotation);
}
}
public void FixedUpdate()
{
PerformMovement();
PerformRotation();
}
}
’‘’