代码
row1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| void LateUpdate()
{
if (camTarget == null)
{
return;
}
float currentRotationAngle = transform.eulerAngles.y;
float wantedRotationAngle = camTarget.eulerAngles.y;
float wantedHeight = camTarget.position.y + height;
float currentHeight = transform.position.y;
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
transform.position = camTarget.position;
transform.position -= currentRotation * Vector3.forward * distance;
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
transform.LookAt(camTarget);
}
|
通常首选在
LateUpdate
而不是
Update
中使用此函数,因为
LateUpdate
在帧中的所有
Update
调用之后运行。以下是它对相机跟随功能产生影响的原因:
确保摄像机位置一致: LateUpdate
确保在所有其他游戏对象(如目标)完成帧的移动或更新后,调整摄像机的位置和旋转。这一点很重要,因为如果在 Update
期间目标的位置或旋转发生变化,并且您也在 Update
中移动摄像机,则可能会出现轻微的滞后或抖动,因为摄像机可能并不总是与最新的目标位置同步。
消除抖动和滞后:通过使用 LateUpdate
,您可以确保在摄像机移动之前考虑目标位置或旋转的任何变化。这使得相机可以平滑、精确地跟随,而不会出现抖动或滞后一帧。
优化摄像机逻辑:在其他更新完成后移动摄像机有助于优化渲染管道。摄像机只需根据对象的最终位置定位自身,这可确保摄像机在帧结束时渲染的内容是准确和最新的。