如何在 Unity 中的 AR 应用程序的 3D 模型上添加按钮?

问题描述 投票:0回答:1

我正在创建一个 AR 医学百科全书作为 Unity 上的入门项目。但是,我无法找到任何解决方案来说明如何在 3D 模型上添加锚定到模型的可点击按钮。

这里有一个链接解释了我的意思:https://www.youtube.com/watch?v=XsIXm5MA3NU

我尝试使用以下方法:https://www.youtube.com/watch?v=tHEG95vrO_Q

当我尝试此方法时,运行它时按钮没有出现。我尝试过将画布设置更改为世界空间和其他多个设置,但它不起作用。

这是我使用的脚本:

using UnityEngine;
using UnityEngine.UI;

public class WorldPositionButton : MonoBehaviour
{
    [SerializeField]
    private Transform targetTransform;

    private RectTransform rectTransform;
    private Image image;
    private Camera mainCamera;

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        image = GetComponent<Image>();
        mainCamera = Camera.main;

        if (targetTransform == null || mainCamera == null)
        {
            enabled = false; // Disable the script if necessary components are missing
            Debug.LogError("Target Transform or Main Camera not assigned!");
        }
    }

    private void Update()
    {
        if (targetTransform == null || mainCamera == null)
            return;

        // Convert world position to screen space
        var screenPoint = mainCamera.WorldToScreenPoint(targetTransform.position);

        // Update UI button position
        rectTransform.position = screenPoint;

        // Check if target is within a certain distance from the center of the screen
        var viewportPoint = mainCamera.WorldToViewportPoint(targetTransform.position);
        var distanceFromCenter = Vector2.Distance(viewportPoint, Vector2.one * 0.5f);

        // Adjust visibility based on distance
        image.enabled = distanceFromCenter < 0.3f;
    }
}

我欢迎尽快提出任何建议。

谢谢你

c# unity-game-engine augmented-reality unity-ui ar-foundation
1个回答
0
投票

您可以尝试将画布设置为世界空间,然后使该画布成为您正在使用的对象的子对象。然后,您可以使用 Transform.Lookat() https://docs.unity3d.com/ScriptReference/Transform.LookAt.html 使画布看着相机,这样它就不会奇怪地旋转,但按钮的位置是正确。

© www.soinside.com 2019 - 2024. All rights reserved.