在 Vuforia 中锚定

Anchoring in Vuforia

我可以在对象生成后修复它的位置。但是,每次点击屏幕时,对象都会放置在不同的位置。我想避免这个问题,并希望我的对象在整个会话或应用程序生命周期中固定在生成的位置。

这是我的 Deploy Stage Once 脚本:

public class DeployStageOnce : MonoBehaviour
{

    public GameObject AnchorStage;
    private PositionalDeviceTracker _deviceTracker;
    private GameObject _anchorGameObject;
    private GameObject _previousAnchor;

    public void Start()
    {
        if (AnchorStage == null)
        {
            Debug.Log("AnchorStage must be specified");
            return;
        }
        AnchorStage.SetActive(false);
    }
    public void Awake()
    {
        VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
    }
    public void OnDestroy()
    {
        VuforiaARController.Instance.UnregisterVuforiaStartedCallback(OnVuforiaStarted);
    }
    private void OnVuforiaStarted()
    {
        _deviceTracker = TrackerManager.Instance.GetTracker<PositionalDeviceTracker>();
    }

    private void AnchorGameObjectSetHitTestPosition(HitTestResult reuslt)

    {

        _anchorGameObject.transform.position = reuslt.Position;

        _anchorGameObject.transform.rotation = reuslt.Rotation;

    }


    public void OnInteractiveHitTest(HitTestResult result)
    {
        if (result == null || AnchorStage == null)
        {
            Debug.LogWarning("Hit test is invalid or AnchorStage not set");
            return;
        }
        var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
        _anchorGameObject = new GameObject();
        AnchorGameObjectSetHitTestPosition(result);
        if (anchor != null)
        {

            AnchorStage.transform.parent = _anchorGameObject.transform;

            AnchorStage.transform.localPosition = Vector3.zero;

            AnchorStage.transform.localRotation = Quaternion.identity;

            AnchorStage.SetActive(true);

                    }
        if (_previousAnchor != null)
        {
            Destroy(_previousAnchor);
        }
        _previousAnchor = _anchorGameObject;
    }
}

那么您可以在脚本中创建一个 isPlaced 变量来检查您的对象是否已经像这样放置:

private bool isPlaced = false;

    public void OnInteractiveHitTest(HitTestResult result)
    {
        if (result == null || AnchorStage == null)
        {
            Debug.LogWarning("Hit test is invalid or AnchorStage not set");
            return;
        }
        if(!isPlaced)
        { 
            var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result);
            _anchorGameObject = new GameObject();
            AnchorGameObjectSetHitTestPosition(result);
            if (anchor != null)
            {

                AnchorStage.transform.parent = _anchorGameObject.transform;

                AnchorStage.transform.localPosition = Vector3.zero;

                AnchorStage.transform.localRotation = Quaternion.identity;

                AnchorStage.SetActive(true);

            }           
            isPlaced = true;
        }
}