在人物模型添加一个空的子物体,作为相机的跟随点,位置大概在胸口。
添加一个虚拟相机
虚拟相机配置如下
在人物模型上添加PlayerInput组件
Action文件配置如下
创建NeirInputs和NeirController脚本并挂载到人物模型上
NeirInputs负责玩家输入
NeirController负责根据输入的值旋转相机
脚本如下
NeirInputs
using UnityEngine;
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
using UnityEngine.InputSystem;
#endif
public class NeirInputs : MonoBehaviour
{
[Header("角色输入值")]
public Vector2 look;
#if !UNITY_IOS || !UNITY_ANDROID
public bool cursorLocked = true;
public bool cursorInputForLook = true;
#endif
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
public void OnLook(InputValue value)
{
if (cursorInputForLook)
{
LookInput(value.Get());
}
}
#else
// old input sys if we do decide to have it (most likely wont)...
#endif
public void LookInput(Vector2 newLookDirection)
{
look = newLookDirection;
}
#if !UNITY_IOS || !UNITY_ANDROID
private void OnApplicationFocus(bool focus)
{
SetCursorState(cursorLocked);
}
private void SetCursorState(bool newState)
{
Cursor.lockState = newState ? CursorLockMode.Locked : CursorLockMode.None;
}
#endif
}
NeirController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class NeirController : MonoBehaviour
{
[Header("虚拟相机")]
[Tooltip("")]
public GameObject CinemachineCameraTarget;
[Tooltip("")]
public float TopClamp = 70.0f;
[Tooltip("")]
public float BottomClamp = -30.0f;
[Tooltip("")]
public float CameraAngleOverrride = 0.0f;
[Tooltip("")]
public bool LockCAmeraPosition = false;
//cinemachine
private float _cinemachineTargetYaw;
private float _cinemachineTargetPitch;
private NeirInputs _input;
private GameObject _mainCamera;
private const float _threshold = 0.01f;
private void Awake()
{
if(_mainCamera == null)
{
_mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
}
}
private void Start()
{
_input = GetComponent();
}
private void LateUpdate()
{
CameraRotation();
}
private void CameraRotation()
{
if(_input.look.sqrMagnitude >= _threshold && !LockCAmeraPosition)
{
_cinemachineTargetYaw += _input.look.x * Time.deltaTime;
_cinemachineTargetPitch += _input.look.y * Time.deltaTime;
}
_cinemachineTargetYaw = ClampAngle(_cinemachineTargetYaw, float.MinValue, float.MaxValue);
_cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
CinemachineCameraTarget.transform.rotation = Quaternion.Euler(_cinemachineTargetPitch + CameraAngleOverrride, _cinemachineTargetYaw, 0.0f);
}
private static float ClampAngle(float lfAngle, float lfMin, float lfMax)
{
if (lfAngle < -360f) lfAngle += 360f;
if (lfAngle > 360f) lfAngle -= 360f;
return Mathf.Clamp(lfAngle, lfMin, lfMax);
}
}



