你好!
我正在尝试解决摄像头抖动的问题。在游戏模式下,无法解决这个问题。
我创建了一个新项目,包含两个简单的脚本:一个用于角色移动,一个用于摄像头控制(围绕角色旋转)。
输入通过新输入系统处理,WASD用于正交移动,鼠标用于摄像头控制。
以下是玩家控制器脚本:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private PlayerInputAction inputActions;
private Vector2 moveInput;
public Transform cameraTransform;
public float speed = 2.5f;
private void Awake()
{
inputActions = new PlayerInputAction();
}
private void OnEnable()
{
inputActions.Player.Enable();
inputActions.Player.Move.performed += ctx => moveInput = ctx.ReadValue<Vector2>();
inputActions.Player.Move.canceled += ctx => moveInput = Vector2.zero;
}
private void OnDisable()
{
inputActions.Player.Disable();
}
void Update()
{
// direction caméra (flat sur le sol)
Vector3 camForward = cameraTransform.forward;
Vector3 camRight = cameraTransform.right;
camForward.y = 0;
camRight.y = 0;
camForward.Normalize();
camRight.Normalize();
// direction de déplacement relative caméra
Vector3 moveDir = camForward * moveInput.y + camRight * moveInput.x;
transform.position += moveDir * speed * Time.deltaTime;
// optionnel : rotation du player vers direction de mouvement
if (moveDir != Vector3.zero)
{
transform.forward = moveDir;
}
}
}
以下是摄像头控制脚本:
using UnityEngine;
using UnityEngine.InputSystem;
public class CameraOrbit : MonoBehaviour
{
[Header("Target")]
public Transform target;
[Header("Settings")]
public float sensitivity = 0.5f;
public float distance = 8f;
public float minY = 30f;
public float maxY = 30f;
private PlayerInputAction input;
private float yaw;
private float pitch;
private Vector2 lookInput;
private void Awake()
{
input = new PlayerInputAction();
}
private void OnEnable()
{
input.Player.Enable();
input.Player.Look.performed += ctx => lookInput = ctx.ReadValue<Vector2>();
input.Player.Look.canceled += ctx => lookInput = Vector2.zero;
}
private void OnDisable()
{
input.Player.Disable();
}
void LateUpdate()
{
if (!target) return;
yaw += lookInput.x * sensitivity;
pitch -= lookInput.y * sensitivity;
pitch = Mathf.Clamp(pitch, minY, maxY);
Quaternion rotation = Quaternion.Euler(pitch, yaw, 0);
Vector3 offset = rotation * new Vector3(0, 0, -distance);
transform.position = target.position + offset;
transform.LookAt(target.position);
}
}
摄像头运动抖动已经存在,出现跳跃等问题,甚至在一个空白的新项目中也存在这些问题。
评论 (0)