forked from oculus-samples/Unity-Phanto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsideSceneChecker.cs
110 lines (89 loc) · 2.79 KB
/
InsideSceneChecker.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
// Copyright (c) Meta Platforms, Inc. and affiliates.
using System;
using System.Collections;
using Phantom.Environment.Scripts;
using UnityEngine;
using UnityEngine.Assertions;
public class InsideSceneChecker : MonoBehaviour
{
private const float MaxCeilingRayLength = 100.0f;
public static event Action<Bounds, bool> UserInSceneChanged;
public static bool UserInScene { get; private set; }
private static Bounds _bounds;
[SerializeField] private SceneBoundsChecker sceneBoundsChecker;
[SerializeField] private OVRCameraRig cameraRig;
private bool _boundsSet;
private void Awake()
{
Assert.IsNotNull(sceneBoundsChecker);
Assert.IsNotNull(cameraRig);
}
private void OnEnable()
{
SceneBoundsChecker.BoundsChanged += OnSceneBoundsChanged;
StartCoroutine(UserBoundsTest());
}
private void OnDisable()
{
SceneBoundsChecker.BoundsChanged -= OnSceneBoundsChanged;
_boundsSet = false;
}
private void OnSceneBoundsChanged(Bounds bounds)
{
_bounds = bounds;
_boundsSet = true;
}
private IEnumerator UserBoundsTest()
{
// check 5 times a second.
var wait = new WaitForSeconds(0.2f);
while (!_boundsSet)
{
yield return null;
}
var head = cameraRig.centerEyeAnchor;
while (enabled)
{
var inBounds = PointInsideScene(head.position);
if (UserInScene != inBounds)
{
UserInScene = inBounds;
UserInSceneChanged?.Invoke(_bounds, inBounds);
}
yield return wait;
}
}
public static bool PointInsideScene(Vector3 position)
{
var inBounds = true;
if (!_bounds.Contains(position))
{
inBounds = false;
}
else // if you are inside the axis-aligned bounding box you could still be outside the scene (e.g. L-shaped room).
{
// cast ray upwards against scene mesh.
// if you didn't hit anything you're outside the scene
// if you hit something and the normal is facing away from you, you're under the scene (basement)
if (!Physics.Raycast(position, Vector3.up, out var hit, MaxCeilingRayLength, NavMeshConstants.SceneMeshLayerMask)
|| Vector3.Dot(hit.normal, position - hit.point) < 0)
{
inBounds = false;
}
}
return inBounds;
}
#if UNITY_EDITOR
private void OnValidate()
{
if (sceneBoundsChecker == null)
{
sceneBoundsChecker = GetComponent<SceneBoundsChecker>();
}
if (cameraRig == null)
{
cameraRig = GetComponentInChildren<OVRCameraRig>(true);
}
}
#endif
}