为角色添加两个脚本 PlayerMotor.cs PlayerController.cs 分开处理输入信息和输出信息
PlayerController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float speed = 5f;
[SerializeField]
private float lookSensitivity = 3f;
private PlayerMotor motor;
// Start is called before the first frame update
void Start()
{
motor = GetComponent<PlayerMotor>();
}
// Update is called once per frame
void Update()
{
float _xMov = Input.GetAxis("Horizontal");
float _zMov = Input.GetAxis("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
// Final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical) * speed;
motor.Move(_velocity);
float _yRot = Input.GetAxisRaw("Mouse X");
Vector3 _rotation = new Vector3(0f, _yRot, 0f) * lookSensitivity;
//Apply rotation
motor.Rotate(_rotation);
float _xRot = Input.GetAxisRaw("Mouse Y");
Vector3 _cameraRotation = new Vector3(_xRot, 0f, 0f) * lookSensitivity;
//Apply camera rotation
motor.RotateCamera(_cameraRotation);
}
}
PlayerMotor.cs:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]//在为物体添加此脚本时自动添加刚体组件
public class PlayerMotor : MonoBehaviour
{
[SerializeField]//序列化使在unity界面可以改动
private Camera cam;
private Vector3 velocity = Vector3.zero;//初始化移动向量
private Vector3 rotation = Vector3.zero;//初始化旋转向量
private Vector3 cameraRotation = Vector3.zero;//初始化相机旋转向量
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void Move(Vector3 _velocity)
{
velocity = _velocity;
}
public void Rotate(Vector3 _rotation)
{
rotation = _rotation;
}
public void RotateCamera(Vector3 _cameraRotation)
{
cameraRotation = _cameraRotation;
}
void FixedUpdate()
{
PerformMovement();
PerformRotation();
}
void PerformMovement()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
void PerformRotation()
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
if (cam != null)
{
cam.transform.Rotate(-cameraRotation);
}
}
}
更新中····