我想要一个 UI Canvas 跟随相机,这样它就会始终位于头部前方,并且可以像 VR 菜单一样进行交互。我正在使用以下代码来执行此操作。
public class FollowMe : MonoBehaviour
{
public GameObject menuCanvas;
public Camera FirstPersonCamera;
[Range(0, 1)]
public float smoothFactor = 0.5f;
// how far to stay away fromt he center
public float offsetRadius = 0.3f;
public float distanceToHead = 4;
public void Update()
{
// make the UI always face towards the camera
menuCanvas.transform.rotation = FirstPersonCamera.transform.rotation;
var cameraCenter = FirstPersonCamera.transform.position + FirstPersonCamera.transform.forward * distanceToHead;
var currentPos = menuCanvas.transform.position;
// in which direction from the center?
var direction = currentPos - cameraCenter;
// target is in the same direction but offsetRadius
// from the center
var targetPosition = cameraCenter + direction.normalized * offsetRadius;
// finally interpolate towards this position
menuCanvas.transform.position = Vector3.Lerp(currentPos, targetPosition, smoothFactor);
}
}
不幸的是, Canvas 在相机前面闪烁并且位置不正确。如何让菜单跟随摄像头移动?|
最佳答案
如果没有理由反对,您可以使用 ScreenSpace - Camera
Canvas ,如所述 in the docs 。然后您可以引用 FPS 相机作为 Canvas 的渲染相机。
关于c# - 使 Canvas 跟随相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60077449/