我想制作一款生存游戏,您可以使用角色控制器在第一人称和第三人称视图之间切换。我遇到了同样的问题。由于地形不平坦,尤其是在岩石附近,相机开始非常猛烈地晃动,以免陷入纹理中。第三人称视角本身,我想让它像游戏中的一样。 视频有问题。脚本:
using UnityEngine;
public class Test : MonoBehaviour
{
[Header("References")]
[SerializeField] private Transform _camera;
private CharacterController _controller;
[Header("Movement Settings")]
[SerializeField] private float _walkSpeed = 5f;
[SerializeField] private float _sprintSpeed = 10f;
[SerializeField] private float _sprintTransitSpeed = 5f;
[SerializeField] private float _gravity = 9.81f;
[SerializeField] private float _jumpHeight = 2f;
private float _verticalVelocity;
private float _currentSpeed;
[Header("Move Input")]
private float _moveInput;
private float _turnInput;
private Vector3 _move;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
_controller = GetComponent<CharacterController>();
}
private void Update()
{
InputManagement();
Movement();
}
private void Movement()
{
GroundMovement();
Turn();
}
private void GroundMovement()
{
_move = new Vector3(_turnInput, 0, _moveInput);
_move = _camera.transform.TransformDirection(_move);
if (Input.GetKey(KeyCode.LeftShift))
{
_currentSpeed = Mathf.Lerp(_currentSpeed, _sprintSpeed, _sprintTransitSpeed * Time.deltaTime);
}
else
{
_currentSpeed = Mathf.Lerp(_currentSpeed, _walkSpeed, _sprintTransitSpeed * Time.deltaTime);
}
_move *= _currentSpeed;
_move.y = VerticalForceCalculation();
_controller.Move(_move * Time.deltaTime);
}
private void Turn()
{
Vector3 currentLookDirection = _camera.forward;
currentLookDirection.y = 0;
transform.rotation = Quaternion.LookRotation(currentLookDirection);
}
private float VerticalForceCalculation()
{
if (_controller.isGrounded)
{
_verticalVelocity = -2f;
if (Input.GetButtonDown("Jump"))
{
_verticalVelocity = Mathf.Sqrt(_jumpHeight * _gravity * 2);
}
}
else
{
_verticalVelocity -= _gravity * Time.deltaTime;
}
return _verticalVelocity;
}
private void InputManagement()
{
_moveInput = Input.GetAxis("Vertical");
_turnInput = Input.GetAxis("Horizontal");
}
}
我在互联网上找不到使用 CharacterController 和 Cinemachine 进行第三人称移动的正常实现。只是原型。