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