如何使用 ARFoundation 与对象交互?



所以这个想法是在增强现实中拥有一个平面和网格放置系统,能够在网格上放置和移动角色。我已经有一个移动设备的例子,我有一个生成网格的脚本和一个允许我放置对象的脚本,它工作得很好,但是,我不知道如何使用上述所有内容以及是否可以在 AR 中。例如,我想检测一个平面,然后实例化一个关卡并在上面放置一些对象。

下面是附加到网格管理器并用于创建网格的脚本:

[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);
}
}
}

下面是附加到 PlacerManager 并用于在网格上放置对象的那个:

private Grid grid;
private void Awake()
{
grid = FindObjectOfType<Grid>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo))
{
PlaceCubeNear(hitInfo.point);
}
}
}
private void PlaceCubeNear(Vector3 clickPoint)
{
var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = finalPosition;
}

您可以使用光线投射选项来识别不同的对象

光线投射和/或对撞机是要走的路。

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);
}
}
}

这使您可以获取屏幕触摸位置,然后从该位置进行光线投射到现实世界的场景。在此示例中,游戏对象在该位置实例化。对于您的情况,如果您击中飞机或命中位置周围存在飞机,您可以实例化关卡。

最新更新