AR Foundation演示项目,使用 AR Foundation 4.1.7 并围绕某些功能演示更高级功能。
您最多选择25个主题 主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

90 行
2.5 KiB

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
[RequireComponent(typeof(ARRaycastManager))]
public class PlaceObjectsOnPlane : MonoBehaviour
{
[SerializeField]
[Tooltip("Instantiates this prefab on a plane at the touch location.")]
GameObject m_PlacedPrefab;
/// <summary>
/// The prefab to instantiate on touch.
/// </summary>
public GameObject placedPrefab
{
get { return m_PlacedPrefab; }
set { m_PlacedPrefab = value; }
}
/// <summary>
/// The object instantiated as a result of a successful raycast intersection with a plane.
/// </summary>
public GameObject spawnedObject { get; private set; }
/// <summary>
/// Invoked whenever an object is placed in on a plane.
/// </summary>
public static event Action onPlacedObject;
ARRaycastManager m_RaycastManager;
static List<ARRaycastHit> s_Hits = new List<ARRaycastHit>();
[SerializeField]
int m_MaxNumberOfObjectsToPlace = 1;
int m_NumberOfPlacedObjects = 0;
[SerializeField]
bool m_CanReposition = true;
public bool canReposition
{
get => m_CanReposition;
set => m_CanReposition = value;
}
void Awake()
{
m_RaycastManager = GetComponent<ARRaycastManager>();
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
if (m_RaycastManager.Raycast(touch.position, s_Hits, TrackableType.PlaneWithinPolygon))
{
Pose hitPose = s_Hits[0].pose;
if (m_NumberOfPlacedObjects < m_MaxNumberOfObjectsToPlace)
{
spawnedObject = Instantiate(m_PlacedPrefab, hitPose.position, hitPose.rotation);
m_NumberOfPlacedObjects++;
}
else
{
if (m_CanReposition)
{
spawnedObject.transform.SetPositionAndRotation(hitPose.position, hitPose.rotation);
}
}
if (onPlacedObject != null)
{
onPlacedObject();
}
}
}
}
}
}