您最多选择25个主题
主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
66 行
1.9 KiB
66 行
1.9 KiB
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.XR.ARFoundation;
|
|
using UnityEngine.XR.ARSubsystems;
|
|
|
|
/// <summary>
|
|
/// Listens for touch events and performs an AR raycast from the screen touch point.
|
|
/// AR raycasts will only hit detected trackables like feature points and planes.
|
|
///
|
|
/// If a raycast hits a trackable, the <see cref="placedPrefab"/> is instantiated
|
|
/// and moved to the hit position.
|
|
/// </summary>
|
|
[RequireComponent(typeof(ARRaycastManager))]
|
|
public class PlaceOnPlane : 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; }
|
|
|
|
void Awake()
|
|
{
|
|
m_RaycastManager = GetComponent<ARRaycastManager>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (Input.touchCount == 0)
|
|
return;
|
|
|
|
var touch = Input.GetTouch(0);
|
|
|
|
if (m_RaycastManager.Raycast(touch.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);
|
|
}
|
|
else
|
|
{
|
|
spawnedObject.transform.position = hitPose.position;
|
|
}
|
|
}
|
|
}
|
|
|
|
static List<ARRaycastHit> s_Hits = new List<ARRaycastHit>();
|
|
|
|
ARRaycastManager m_RaycastManager;
|
|
}
|