当前位置:网站首页>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
边栏推荐
- The method and detailed code of automatically pop-up and QQ group when players visit the website
- SM integration is as simple as before, and the steps are clear (detailed)
- The song of the virtual idol was originally generated in this way!
- Pytorch learning notes
- Big silent event Google browser has no title
- 【2022新生学习】第三周要点
- Mapper agent development
- 优炫数据库启动失败,报网络错误
- 时间序列分析的表示学习时代来了?
- 传奇开区网站如何添加流量统计代码
猜你喜欢

ARFoundation从零开始9-AR锚点(AR Anchor)

How to add traffic statistics codes to the legendary Development Zone website

开源汇智创未来 | 2022开放原子全球开源峰会 openEuler 分论坛圆满召开

Excel怎么筛选出自己想要的内容?excel表格筛选内容教程

How to install Office2010 installation package? How to install Office2010 installation package on computer
![[wechat applet -- solve the alignment problem of the last line of display:flex. (discontinuous arrangement will be divided into two sides)]](/img/ee/b424d876c64dac652d76f9f26e4b20.png)
[wechat applet -- solve the alignment problem of the last line of display:flex. (discontinuous arrangement will be divided into two sides)]

Arfoundation starts from zero 9-ar anchor

Diagram of odoo development tutorial
Let you understand several common traffic exposure schemes in kubernetes cluster

The person who goes to and from work on time and never wants to work overtime has been promoted in front of me
随机推荐
AUTOSAR从入门到精通100讲(七十八)-AUTOSAR-DEM模块
Stack and queue and priority queue (large heap and small heap) simulation implementation and explanation of imitation function
How does WPS use smart fill to quickly fill data? WPS method of quickly filling data
Reply from the Secretary of jindawei: the company is optimistic about the market prospect of NMN products and has launched a series of products
时间序列分析的表示学习时代来了?
Soft link & hard link
How to add a map to the legendary server
AttributeError: ‘module‘ object has no attribute ‘create_ connection‘
IDEA中使用注解Test
SM integration is as simple as before, and the steps are clear (detailed)
WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
JS (foreach) return cannot end the function solution
学习数据库的第一个程序
带你搞懂 Kubernetes 集群中几种常见的流量暴露方案
Mysql把查询到的结果集按指定顺寻进行排序
深度学习刷SOTA的一堆trick
7.1-default-arguments
The representation of time series analysis: is the era of learning coming?
优炫数据库启动失败,报网络错误