using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 10.0f;
public float gravity = -9.81f;
public float jumpHeight = 3.0f;
public float mouseSensitivity = 100.0f;
public Transform playerBody;
private CharacterController controller;
private Vector3 velocity;
private float xRotation = 0f;
void Start()
{
controller = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
}
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);
Debug.Log("Mouse X: " + mouseX);
Debug.Log("Mouse Y: " + mouseY);
Debug.Log("Local Rotation Before: " + transform.localRotation);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
Debug.Log("Local Rotation After: " + transform.localRotation);
playerBody.Rotate(Vector3.up * mouseX);
if (controller.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") && controller.isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
Debug.Log("Mouse X: " + mouseX);
Debug.Log("Mouse Y: " + mouseY);
Debug.Log("Local Rotation: " + transform.localRotation);
}
}
视频:https://youtu.be/c2iGfd8AqH0 当我在 Y 轴上旋转相机时,我看到它旋转并立即返回到零点。
我尝试重写相机运动,但现在它只沿着 Y 轴旋转。我该怎么办?
我问过我的朋友,他们自己也不知道。
我有一个猜测!假设您正在遵循的教程按照我认为的方式工作,Y 轴旋转是由玩家的身体完成的,而 X 轴旋转是在具有相机组件的子对象上完成的。
我的猜测是,在教程中,移动脚本是玩家身体的组件,鼠标外观脚本是相机的组件!您的代码将它们放在同一个对象上,因此旋转逻辑混乱,并且它们互相覆盖。
相反,应分别旋转它们。 CameraHolder 应该是相机的 Transform 组件。相机应该是playerBody的子级。
Debug.Log("Local Rotation Before: " + cameraHolder.localRotation);
cameraHolder.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
Debug.Log("Local Rotation After: " + transform.localRotation);
playerBody.Rotate(Vector3.up * mouseX);