当前位置:网站首页>Getting started with arfoundation tutorial 10- plane detection and placement
Getting started with arfoundation tutorial 10- plane detection and placement
2022-07-29 05:17:00 【suelee_ hm】
Sample source code :
https://github.com/sueleeyu/ar-plane
from 《ARFoundation Starting from scratch 3-arfoundation project 》 Copy project , continue :
One 、 Add the component
1. add to AR RayCaset Manager and AR Plane Manager:
Select left Hierarchy-AR Session Origin,Inspector Next click Add Component, Enter and add in sequence AR RayCaset Manager and AR Plane Manager
2. Create a plane prefabs:Hierarchy-‘+’-XR-AR Default Plane,Assets Under the new Prefabs Catalog , Drag the created object to Prefabs Catalog , Delete Hieraychy The next object .
3. Will create the plane Drag the preform to Plane Manager Components :
4. establish Button Components , name BtnPlane, Used for display / Hide plane :
Two 、 Write code
1. To write cs Code PlaceManager.cs, Used to place prefabricated parts .
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
namespace FrameworkDesign.Example
{
public class PlaceManager : MonoBehaviour
{
[Header("AR Foundation")]
/// <summary>
/// The active ARRaycastManager used in the example.
/// </summary>
public ARRaycastManager m_RaycastManager;
[Header("UI")]
[SerializeField]
[Tooltip("Instantiates this prefab on a plane at the touch location.")]
GameObject m_PlacedPrefab;// Precast units to be placed
/// <summary>
/// The prefab to instantiate on touch.
/// </summary>
public GameObject placedPrefab
{
get { return m_PlacedPrefab; }
set { m_PlacedPrefab = value; }
}
[HideInInspector]
static List<ARRaycastHit> s_Hits = new List<ARRaycastHit>();// Store the detected collision points
/// <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>();// It can also be done through GetComponent Get ARRaycastManager
}
bool TryGetTouchPosition(out Vector2 touchPosition)
{
if (Input.touchCount > 0)
{
touchPosition = Input.GetTouch(0).position;
return true;
}
touchPosition = default;
return false;
}
void Update()
{
if (!TryGetTouchPosition(out Vector2 touchPosition))
return;
var touch = Input.GetTouch(0);
const TrackableType trackableTypes =
TrackableType.FeaturePoint |
TrackableType.PlaneWithinPolygon;
if (Input.touchCount == 1 && touch.phase == TouchPhase.Moved)// Move the placed object
{
if (m_RaycastManager.Raycast(touchPosition, s_Hits, trackableTypes))
{
// 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.transform.position = hitPose.position;
}
}
}
if (Input.touchCount == 1 && touch.phase == TouchPhase.Began)// testing touch begin, stay touch begin Do ray collision detection in
{
//--- Determine whether touch To UI Components ----
//#if IPHONE || ANDROID
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
//#else
// if (EventSystem.current.IsPointerOverGameObject())
//#endif
//Debug.Log(" Current touch in UI On ");
{
Logger.Log($" Current touch in UI On "+ touch.phase);
return;
}
else
{
//Debug.Log(" There is currently no touch in UI On ");
Logger.Log($" There is currently no touch in UI On "+ touch.phase);
}
if (m_RaycastManager.Raycast(touchPosition, s_Hits, trackableTypes))
{
// 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);// Instantiate the preform object
}
else
{
spawnedObject.transform.position = hitPose.position;// Update object status
}
}
}
}
}
}
2.Hierarchy Next Game Next Create Empty, name GameScene, take PlaneManager.cs Mount to it :
choice ARScene, take AR Session Origin And the prefabricated parts are towed to PlaceManager.cs Parameter column of :
3. To write ARManager.cs, Used for display / Hide plane information :
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
public class ARManager : MonoBehaviour
{
[Header("AR Foundation")]
/// <summary>
/// The active ARRaycastManager used in the example.
/// </summary>
public ARPlaneManager m_ARPlaneManager;
[HideInInspector]
/// <summary>
/// Currently recognized plane
/// </summary>
List<ARPlane> detectPlanes = new List<ARPlane>();
/// <summary>
/// Whether to display the plane at present
/// </summary>
bool isShowPlane = true;
#region MonoBehaviour CallBacks
private void Awake()
{
m_ARPlaneManager = FindObjectOfType<ARPlaneManager>();
}
void Start()
{
CheckDevice();
m_ARPlaneManager.planesChanged += OnPlaneChanged;
}
private void Update()
{
SaveElePolicy();
}
void OnDisable()
{
m_ARPlaneManager.planesChanged -= OnPlaneChanged;
}
#endregion
// Enable and disable plane detection
// The program is enabled by default , When enabled, the plane is constantly detected . When it is closed, the new plane will not be detected .
public void DetectionPlane(bool value)
{
m_ARPlaneManager.enabled = value;
if (m_ARPlaneManager.enabled)
{
print(" Plane detection enabled ");
}
else
{
print(" Plane detection is disabled ");
}
}
// Show and hide the detected plane
public void SwitchPlane()
{
isShowPlane = !isShowPlane;
for (int i = detectPlanes.Count - 1; i >= 0; i--)
{
if (detectPlanes[i] == null || detectPlanes[i].gameObject == null)
detectPlanes.Remove(detectPlanes[i]);
else
detectPlanes[i].gameObject.SetActive(isShowPlane);
}
}
/// <summary>
/// Get the present AR Whether the session is running , And be tracked ( namely , The device can determine its position and direction in the world ).
/// </summary>
public bool Skode_IsTracking()
{
bool isTracking = false;
if (ARSession.state == ARSessionState.SessionTracking)
{
isTracking = true;
}
return isTracking;
}
// stay ARFoundation When a plane is newly discovered , Add the plane to the list , It is convenient for us to control these planes
void OnPlaneChanged(ARPlanesChangedEventArgs arg)
{
for (int i = 0; i < arg.added.Count; i++)
{
detectPlanes.Add(arg.added[i]);
arg.added[i].gameObject.SetActive(isShowPlane);
}
}
// Check the operating environment of the equipment
void CheckDevice()
{
if (ARSession.state == ARSessionState.NeedsInstall)
{
ShowAndroidToastMessage("AR is supported, but requires an additional install. .");
Invoke("Quit", 1);
}
else if (ARSession.state == ARSessionState.Ready)
{
Debug.Log("AR is supported and ready.");
}
else if (ARSession.state == ARSessionState.Unsupported)
{
ShowAndroidToastMessage("AR is not supported on the current device.");
Invoke("Quit", 1);
}
}
void ShowAndroidToastMessage(string message)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
if (unityActivity != null)
{
AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
AndroidJavaObject toastObject = toastClass.CallStatic<AndroidJavaObject>("makeText", unityActivity, message, 0);
toastObject.Call("show");
}));
}
}
void Quit()
{
Application.Quit();
}
/// <summary>
/// A power saving setting , When the device fails to find the identification target , Allow the screen to darken after the last period of activation
/// </summary>
void SaveElePolicy()
{
if (ARSession.state != ARSessionState.SessionTracking)
{
const int lostTrackingSleepTimeout = 15;
Screen.sleepTimeout = lostTrackingSleepTimeout;
}
else
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
}
}
4. add to ARManager.cs To Hierarchy-Game Next , mount PlaneManager Components :
5. add to Button Of click event . choice BtnPlane Components , add to Onclick event , Drag the Game, choice Function function :
Two 、unity Knowledge point
1. Radiographic testing ARRaycastManager:
ARRaycastManager.Raycast(Vector2, List<ARRaycastHit>, TrackableType) .
API:Class ARRaycastManager | AR Foundation | 4.2.3
Be careful : Not all TrackableType
All suffer ARCore and ARKit Provider support .ARCore The provider currently only supports PlaneEstimated
、PlaneWithinBounds
、PlaneWithinPolygon
、FeaturePoint
、Image
and Depth
.
3、 ... and 、android Packaging operation
If not configured , see 《ARFoundation Starting from scratch 3-arfoundation project 》.
1. Installation and operation
Four 、 common problem
5、 ... and 、 Reference material
1. Unity api:
Class ARRaycastManager | AR Foundation | 4.2.3
2.ARFoundation Example :
3.ARCore file :
stay Unity (AR Foundation) Perform ray casting in the application | ARCore | Google Developers
4. The sample source code of this project :
https://github.com/sueleeyu/ar-plane
边栏推荐
- [sudden] solve remote: support for password authentication was removed on August 13, 2021. please use a perso
- Architecture analysis of three-tier project and parameter name injection of construction method
- scikit-learn——机器学习应用开发的步骤和理解
- 深度学习刷SOTA的一堆trick
- The song of the virtual idol was originally generated in this way!
- Ros1 dead chicken data is stored in txt and SQLite
- TCP三次握手四次挥手
- AUTOSAR从入门到精通100讲(七十八)-AUTOSAR-DEM模块
- Unity metaverse (III), protobuf & socket realize multi person online
- About the configuration and use of thymeleaf
猜你喜欢
随机推荐
SM integration is as simple as before, and the steps are clear (detailed)
P2181 diagonal
缓存穿透、缓存击穿、缓存雪崩以及解决方法
ARFoundation从零开始3-创建ARFoundation项目
WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
Five correlation analysis, one of the most important skills of data analysts
虚拟偶像的歌声原来是这样生成的!
AttributeError: ‘module‘ object has no attribute ‘create_connection‘
向往的开源之多YOUNG新生 | 从开源到就业的避坑指南来啦!
ARFoundation从零开始8-Geospatial API(地理空间)开发
Understand activity workflow
Let you understand several common traffic exposure schemes in kubernetes cluster
优炫数据库启动失败,报网络错误
Word如何查看文档修改痕迹?Word查看文档修改痕迹的方法
How to add traffic statistics codes to the legendary Development Zone website
电脑无法打开excel表格怎么办?excel打不开的解决方法
Apache POI implements excel import, read data, write data and export
Office提示系统配置无法运行怎么办?
Do you remember the process analysis and function implementation of post notification?
What if excel is stuck and not saved? The solution of Excel not saved but stuck