AR Foundation 即时展示位置开发者指南

了解如何在您自己的应用中使用 Instant Placement API(即持久性射线投射)。

前提条件

在继续操作之前,请确保您了解基本 AR 概念以及如何配置 ARCore 会话

概念名称

AR Foundation 和 ARCore SDK for Unity 中的某些概念和方法的名称可能有所不同。下表列出了这些值,以便您轻松参考。

前提条件

本指南假定您已安装并配置 Unity。如果没有,请参阅 AR Foundation 的 ARCore Extensions 使用入门,了解安装和设置步骤。

使用 ARRaycastManager 配置新会话

借助 AR Foundation 软件包,您可以直接使用即时放置(永久性射线投射)。请按照以下步骤设置场景。

  1. 添加预定义游戏对象 XR OriginAR Session

  2. AR Raycast Manager 组件添加到 XR Origin 游戏对象中。

当 Raycast 预制体不为 null 时,ARRaycastManager 会实例化该预制体,并自动将其姿势与 ARRaycast 的姿势同步。

  1. 添加预定义游戏对象 XR OriginAR Session

  2. AR Raycast Manager 组件添加到 XR Origin 游戏对象中。

当 Raycast 预制体不为 null 时,ARRaycastManager 会实例化该预制体,并自动将其姿势与 ARRaycast 的姿势同步。

放置对象

在新 ARCore 会话中,使用 ARRaycastManager.AddRaycast(Vector2, float) 执行点击测试。

public ARRaycastManager RaycastManager; // set from the Editor Inspector.

void Update()
{
    Touch touch;
    if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
    {
        return;
    }

    if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
    {
        return;
    }

    ARRaycast raycast = RaycastManager.AddRaycast(touch.position, _estimateDistance);
    if (raycast != null)
    {
        // You can instantiate a 3D object here if you haven’t set Raycast Prefab in the scene.
        
    }
}

监控 ARRaycast 跟踪状态

如果 ARCore 具有准确的 3D 姿势,则 ARRaycast.trackingState 将为 Tracking。否则,它将从 Limited 开始,并在 ARCore 获得准确的 3D 姿势后转换为 Tracking。跟踪状态变为 Tracking 后,便不会再变回 Limited