【发布时间】:2021-01-12 19:35:09
【问题描述】:
我使用附加的 c# 脚本来控制相机。
鼠标滚动(滑轮/滚轮/滚轮):放大和缩小主角
上箭头(或 W 键)和下箭头(或 X 键):升高和降低相机
右箭头(或 D 键)和左箭头(或 A 键):围绕主角旋转相机
我试图让相机跟随主角的背部,并添加玩家使用鼠标和箭头定义的偏移量。
此行根据鼠标和箭头的输入正确移动相机:
transform.position = target.position + offset * currentZoom;
这条线正确地移动了相机,使其跟随主角的背部:
transform.position = target.position - target.forward + Vector3.up;
但只有当另一个被取消时,它们才能正常工作。如果我尝试将它们合并为一行,例如:
transform.position = target.position - target.forward + Vector3.up + offset * currentZoom;
然后相机无法正常移动:
-
使用左箭头和右箭头可围绕主画面移动相机 椭圆/椭圆形而不是圆形的字符
-
角色移动时,左右设置的偏移量 箭头未保存,但相机返回到正后方 主角的背影
我需要做些什么来合并两条线才能使相机正确移动?
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
public Vector3 offset = new Vector3(10f, 6f, 0f);
public float RotationX = .5f;
public float rightLeftSpeed = 5f;
public float currentZoom = .13f;
public float minZoom = .1f;
public float maxZoom = 1f;
public float speedZoom = .1f;
public float currentHeight = 6f;
public float minHeight = 0f;
public float maxHeight = 10f;
public float speedHeight = 1f;
void Update()
{
currentZoom -= Input.GetAxis("Mouse ScrollWheel") * speedZoom;
currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);
currentHeight += Input.GetAxis("Vertical") * speedHeight * Time.deltaTime;
currentHeight = Mathf.Clamp(currentHeight, minHeight, maxHeight);
offset.y = currentHeight;
offset = Quaternion.AngleAxis(-Input.GetAxis("Horizontal") * rightLeftSpeed, Vector3.up) * offset;
}
void LateUpdate()
{
transform.position = target.position + offset * currentZoom;
transform.position = target.position - target.forward + Vector3.up;
transform.LookAt(target.position + Vector3.up * RotationX);
}
}
【问题讨论】:
-
作为一般规则,从不使用 LateUpdate。如果您在 LateUpdate 中搞砸了,您将永远无法实现您的目标。建议作为第一步,重新开始,但不要出于任何原因使用 LateUpdate
-
@Fattie 什么?为什么他们不能使用 LateUpdate?
-
我也加入了这个问题。在 Unity 官方网站文档中,它说:“相机应始终在 LateUpdate 中实现”。 docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html
-
我多年来一直使用延迟更新而没有问题。它实际上只是在执行顺序后面发生的更新。相机的东西很适合后期更新,因为它可以确保它所跟随的对象在移动相机之前处于帧的最终位置。