当前位置:网站首页>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
边栏推荐
- JS daily question (12)
- JDBC statement + resultset introduction
- Unity metaverse (III), protobuf & socket realize multi person online
- office2010每次打开都要配置进度怎么解决?
- What if the office prompts that the system configuration cannot run?
- 关于servlet中实现网站的页面跳转
- Deadlock to be resolved
- VirtualBox has expanded the capacity of virtual hard disk (without modifying the original data)
- 2022年泰迪杯数据挖掘挑战赛C题方案及赛后总结
- Deadlock analysis using jstack, jconsole, and jvisualvm
猜你喜欢
Deep learning brush a bunch of tricks of SOTA
传奇服务端如何添加地图
[untitled]
[untitled]
Functions in MySQL statements
What if the office prompts that the system configuration cannot run?
The representation of time series analysis: is the era of learning coming?
Word如何查看文档修改痕迹?Word查看文档修改痕迹的方法
Arfoundation starts from scratch 3- create an arfoundation project
6.3 references
随机推荐
Excel怎么筛选出自己想要的内容?excel表格筛选内容教程
源码编译pytorch坑
ARFoundation入门教程7-url动态加载图像跟踪库
Arfoundation starts from scratch 3- create an arfoundation project
Use annotation test in idea
SQL log
JDBC statement + resultset introduction
Create a mindscore environment in modelars, install mindvision, and conduct in-depth learning and training (Huawei)
学习数据库的第一个程序
What servers are needed to build mobile app
How to install Office2010 installation package? How to install Office2010 installation package on computer
ODOO开发教程之图表
Sparksql inserts or updates in batches and saves data to MySQL
Numpy Foundation
Ros1 dead chicken data is stored in txt and SQLite
Google gtest事件机制
Raspberry pie 4B + Intel neural computing stick (stick2) +yolov5 feasibility study report
【config】配置数组参数
Activity workflow table structure learning
How to add a map to the legendary server