c# - 使 Canvas 跟随相机

标签 c# unity-game-engine user-interface menu virtual-reality

我想要一个 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/

相关文章:

c# - 如何以编程方式发现系统上映射的网络驱动器及其服务器名称?

unity-game-engine - 检查相机是否面向特定方向

c# - 如何从 Unity 上的 C# 静态类获取当前文件夹

javascript - 打开Twitter之类的供稿页面的元素网页 'on top'

c# - 用于 C# 的 Selenium WebDriver - 弹出对话框

c# - wpf 绑定(bind)不更新

c# - 将 C++ COM 类转换为 C# 以供 C++ 可执行文件调用

python - 如何使用 python 和 unity3d C# 比较图像的哈希值?

java - 读取文本文件(我已经知道)然后在 GUI 中显示它?

c++ - 将多个数据存储到一个文件中