发现CSDN上面相当一部分“移动镜头旋转”脚本不好用,我就自己发一个吧。
/// <summary>
/// 注意不要把Rigbody的静态力学打开。否则会导致功能不正常。
/// </summary>
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
public static PlayerController instance;
[SerializeField] private float moveSpeed = 5.0f;
[SerializeField] private float mouseSensitivity = 2.0f;
[SerializeField] private float gravity = -9.81f;
private CharacterController characterController;
private Transform cameraTransform;
private float verticalRotation = 0f;
private float verticalVelocity = 0f;
private bool isRotating = false;
public bool Alowmove;
private void Awake()
{
Alowmove=true;
instance = this;
}
void Start()
{
characterController = GetComponent<CharacterController>();
cameraTransform = Camera.main.transform;
}
void Update()
{
if(Alowmove)
{
// Handle gravity
if (characterController.isGrounded)
{
verticalVelocity = 0; // Reset on ground
}
else
{
verticalVelocity += gravity * Time.deltaTime; // Apply gravity
}
// Player movement
float forwardSpeed = Input.GetAxis("Vertical") * moveSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * moveSpeed;
Vector3 speed = new Vector3(sideSpeed, verticalVelocity, forwardSpeed);
speed = transform.rotation * speed;
characterController.Move(speed * Time.deltaTime);
// Player rotation
if (Input.GetMouseButtonDown(1)) // Rotate on right click
{
isRotating = true;
}
else if (Input.GetMouseButtonUp(1)) // Stop rotating on release
{
isRotating = false;
}
if (isRotating)
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = -Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation += mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
transform.Rotate(0, mouseX, 0);
cameraTransform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
}
}
}
}