找到的一个制作纪念碑谷的项目,项目里写了一些node来控制角色移动,其中用这些代码实现当角色移动的让角色面向下一个结点。这个代码传入了当前角色所处的结点和下一个要经过的结点,然后将下一个结点的位置转为了屏幕空间,声明了一条射线从相机到这个屏幕空间的点,然后在角色脚底创建了一个平面,通过Raycast方法获取了到相机的距离,同时获取射线上这个距离点的坐标,用开始结点减去了这个坐标再让角色向这个坐标旋转。
我没有理解的是,为什么要通过这些步骤去获取这个坐标,而不是直接用开始坐标减去下一个坐标然后直接让角色旋转。
图中的黑点就是node,角色每次行走都会走到node的位置上。
```c#
public void FaceNextPosition(Vector3 startPosition, Vector3 nextPosition)
{
if (Camera.main == null)
{
return;
}
// convert next Node world space to screen space
Vector3 nextPositionScreen = Camera.main.WorldToScreenPoint(nextPosition);
// convert next Node screen point to Ray
Ray rayToNextPosition = Camera.main.ScreenPointToRay(nextPositionScreen);
// plane at player's feet
Plane plane = new Plane(Vector3.up, startPosition);
// distance from camera (used for projecting point onto plane)
float cameraDistance = 0f;
// project the nextNode onto the plane and face toward projected point
if (plane.Raycast(rayToNextPosition, out cameraDistance))
{
Vector3 nextPositionOnPlane = rayToNextPosition.GetPoint(cameraDistance);
Vector3 directionToNextNode = nextPositionOnPlane - startPosition;
if (directionToNextNode != Vector3.zero)
{
transform.rotation = Quaternion.LookRotation(directionToNextNode);
}
}
}