Advertisement
Guest User

AR

a guest
Oct 22nd, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.87 KB | None | 0 0
  1. //-----------------------------------------------------------------------
  2. // <copyright file="HelloARController.cs" company="Google">
  3. //
  4. // Copyright 2017 Google Inc. All Rights Reserved.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. // </copyright>
  19. //-----------------------------------------------------------------------
  20.  
  21. namespace GoogleARCore.Examples.HelloAR
  22. {
  23. using System.Collections.Generic;
  24. using GoogleARCore;
  25. using GoogleARCore.Examples.Common;
  26. using UnityEngine;
  27. using UnityEngine.EventSystems;
  28.  
  29. #if UNITY_EDITOR
  30. // Set up touch input propagation while using Instant Preview in the editor.
  31. using Input = InstantPreviewInput;
  32. #endif
  33.  
  34. /// <summary>
  35. /// Controls the HelloAR example.
  36. /// </summary>
  37. public class HelloARController : MonoBehaviour
  38. {
  39. /// <summary>
  40. /// The first-person camera being used to render the passthrough camera image (i.e. AR
  41. /// background).
  42. /// </summary>
  43. public Camera FirstPersonCamera;
  44.  
  45. /// <summary>
  46. /// A prefab for tracking and visualizing detected planes.
  47. /// </summary>
  48. public GameObject DetectedPlanePrefab;
  49.  
  50. /// <summary>
  51. /// A model to place when a raycast from a user touch hits a vertical plane.
  52. /// </summary>
  53. public GameObject DicodingVerticalPlanePrefab;
  54.  
  55. /// <summary>
  56. /// A model to place when a raycast from a user touch hits a horizontal plane.
  57. /// </summary>
  58. public GameObject DicodingHorizontalPlanePrefab;
  59.  
  60. /// <summary>
  61. /// A model to place when a raycast from a user touch hits a feature point.
  62. /// </summary>
  63. public GameObject AndroidGreenPointPrefab;
  64.  
  65. /// <summary>
  66. /// The rotation in degrees need to apply to model when the Andy model is placed.
  67. /// </summary>
  68. private const float k_ModelRotation = 180.0f;
  69.  
  70. /// <summary>
  71. /// True if the app is in the process of quitting due to an ARCore connection error,
  72. /// otherwise false.
  73. /// </summary>
  74. private bool m_IsQuitting = false;
  75.  
  76. /// <summary>
  77. /// The Unity Awake() method.
  78. /// </summary>
  79. public void Awake()
  80. {
  81. // Enable ARCore to target 60fps camera capture frame rate on supported devices.
  82. // Note, Application.targetFrameRate is ignored when QualitySettings.vSyncCount != 0.
  83. Application.targetFrameRate = 60;
  84. }
  85.  
  86. /// <summary>
  87. /// The Unity Update() method.
  88. /// </summary>
  89. public void Update()
  90. {
  91. _UpdateApplicationLifecycle();
  92.  
  93. // If the player has not touched the screen, we are done with this update.
  94. Touch touch;
  95. if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
  96. {
  97. return;
  98. }
  99.  
  100. // Should not handle input if the player is pointing on UI.
  101. if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
  102. {
  103. return;
  104. }
  105.  
  106. // Raycast against the location the player touched to search for planes.
  107. TrackableHit hit;
  108. TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
  109. TrackableHitFlags.FeaturePointWithSurfaceNormal;
  110.  
  111. if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
  112. {
  113. // Use hit pose and camera pose to check if hittest is from the
  114. // back of the plane, if it is, no need to create the anchor.
  115. if ((hit.Trackable is DetectedPlane) &&
  116. Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
  117. hit.Pose.rotation * Vector3.up) < 0)
  118. {
  119. Debug.Log("Hit at back of the current DetectedPlane");
  120. }
  121. else
  122. {
  123. // Choose the Andy model for the Trackable that got hit.
  124. GameObject prefab;
  125. if (hit.Trackable is FeaturePoint)
  126. {
  127. prefab = AndroidGreenPointPrefab;
  128. }
  129. else if (hit.Trackable is DetectedPlane)
  130. {
  131. DetectedPlane detectedPlane = hit.Trackable as DetectedPlane;
  132. if (detectedPlane.PlaneType == DetectedPlaneType.Vertical)
  133. {
  134. prefab = DicodingVerticalPlanePrefab;
  135. }
  136. else
  137. {
  138. prefab = DicodingHorizontalPlanePrefab;
  139. }
  140. }
  141. else
  142. {
  143. prefab = DicodingHorizontalPlanePrefab;
  144. }
  145.  
  146. // Instantiate Andy model at the hit pose.
  147. var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
  148.  
  149. // Compensate for the hitPose rotation facing away from the raycast (i.e.
  150. // camera).
  151. andyObject.transform.Rotate(0, k_ModelRotation, 0, Space.Self);
  152.  
  153. // Create an anchor to allow ARCore to track the hitpoint as understanding of
  154. // the physical world evolves.
  155. var anchor = hit.Trackable.CreateAnchor(hit.Pose);
  156.  
  157. // Make Andy model a child of the anchor.
  158. andyObject.transform.parent = anchor.transform;
  159. }
  160. }
  161. }
  162.  
  163. /// <summary>
  164. /// Check and update the application lifecycle.
  165. /// </summary>
  166. private void _UpdateApplicationLifecycle()
  167. {
  168. // Exit the app when the 'back' button is pressed.
  169. if (Input.GetKey(KeyCode.Escape))
  170. {
  171. Application.Quit();
  172. }
  173.  
  174. // Only allow the screen to sleep when not tracking.
  175. if (Session.Status != SessionStatus.Tracking)
  176. {
  177. Screen.sleepTimeout = SleepTimeout.SystemSetting;
  178. }
  179. else
  180. {
  181. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  182. }
  183.  
  184. if (m_IsQuitting)
  185. {
  186. return;
  187. }
  188.  
  189. // Quit if ARCore was unable to connect and give Unity some time for the toast to
  190. // appear.
  191. if (Session.Status == SessionStatus.ErrorPermissionNotGranted)
  192. {
  193. _ShowAndroidToastMessage("Camera permission is needed to run this application.");
  194. m_IsQuitting = true;
  195. Invoke("_DoQuit", 0.5f);
  196. }
  197. else if (Session.Status.IsError())
  198. {
  199. _ShowAndroidToastMessage(
  200. "ARCore encountered a problem connecting. Please start the app again.");
  201. m_IsQuitting = true;
  202. Invoke("_DoQuit", 0.5f);
  203. }
  204. }
  205.  
  206. /// <summary>
  207. /// Actually quit the application.
  208. /// </summary>
  209. private void _DoQuit()
  210. {
  211. Application.Quit();
  212. }
  213.  
  214. /// <summary>
  215. /// Show an Android toast message.
  216. /// </summary>
  217. /// <param name="message">Message string to show in the toast.</param>
  218. private void _ShowAndroidToastMessage(string message)
  219. {
  220. AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  221. AndroidJavaObject unityActivity =
  222. unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  223.  
  224. if (unityActivity != null)
  225. {
  226. AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
  227. unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
  228. {
  229. AndroidJavaObject toastObject =
  230. toastClass.CallStatic<AndroidJavaObject>(
  231. "makeText", unityActivity, message, 0);
  232. toastObject.Call("show");
  233. }));
  234. }
  235. }
  236. }
  237. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement