如何使用ARFoundation与对象进行交互?

时间:2020-05-31 23:51:44

标签: c# unity3d augmented-reality arkit arcore

因此,我们的想法是在增强现实中拥有一个平面和网格放置系统,并能够在网格上放置和移动角色。我已经有一个用于移动设备的示例,我有一个生成网格的脚本和一个允许我放置对象的脚本,它可以正常工作,但是,我不知道如何使用以上所有内容,如果在AR中可能。例如,我要检测一个平面,然后实例化一个水平并将一些对象放在其上。

这是GridManager附带的脚本,用于创建网格:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="position-relative">
  <img class="w-100 d-block" src="https://via.placeholder.com/400x300/007bff/ffffff" alt="">
  <div id="overlay">
    <input class="form-control" placeholder="Lorem Ipsum">
    <hr>
    <textarea class="form-control" placeholder="Lorem Ipsum"></textarea>
  </div>
</div>

这是附加到PlacerManager并用于在网格上放置对象的对象:

[SerializeField] private float size = 0.05f;

public Vector3 GetNearestPointOnGrid(Vector3 position)
{
    position -= transform.position;

    int xCount = Mathf.RoundToInt(position.x / size);
    int yCount = Mathf.RoundToInt(position.y / size);
    int zCount = Mathf.RoundToInt(position.z / size);

    Vector3 result = new Vector3(
        (float)xCount * size,
        (float)yCount * size,
        (float)zCount * size);

    result += transform.position;

    return result;
}

private void OnDrawGizmos()
{
    Gizmos.color = Color.yellow;
    for (float x = 0; x < 40; x += size)
    {
        for (float z = 0; z < 40; z += size)
        {
            var point = GetNearestPointOnGrid(new Vector3(x, 0f, z));
            Gizmos.DrawSphere(point, 0.01f);
        }

    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用raycast选项来识别不同的对象

答案 1 :(得分:0)

光线投射和/或对撞机是解决之道。

AR Foundation中的示例场景具有一个名为PlaceOnPlane.cs的脚本,该脚本显示了如何检测用户何时触摸屏幕。例如:

if (Input.touchCount == 1) {
        if (m_RaycastManager.Raycast(Input.GetTouch(0).position, s_Hits, TrackableType.PlaneWithinPolygon))
            {
                // Raycast hits are sorted by distance, so the first one
                // will be the closest hit.
                var hitPose = s_Hits[0].pose;

                if (spawnedObject == null)
                {
                    spawnedObject = Instantiate(m_PlacedPrefab, hitPose.position, hitPose.rotation);
                }
            }
}

这使您可以获取屏幕触摸位置,然后将其从光线投射到现实世界场景中。在此示例中,游戏对象在该位置被实例化。对于您的情况,如果您命中某个平面或某个平面位于命中位置周围,则可以实例化一个关卡。