-
Notifications
You must be signed in to change notification settings - Fork 83
/
WorldBeyondManager.cs
1588 lines (1442 loc) · 62.5 KB
/
WorldBeyondManager.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* Licensed under the Oculus SDK License Agreement (the "License");
* you may not use the Oculus SDK except in compliance with the License,
* which is provided at the time of installation or download, or which
* otherwise accompanies this software in either electronic or hard copy form.
*
* You may obtain a copy of the License at
*
* https://developer.oculus.com/licenses/oculussdk/
*
* Unless required by applicable law or agreed to in writing, the Oculus SDK
* 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using Oculus.Interaction;
using Oculus.Interaction.DistanceReticles;
using UnityEngine;
using Random = UnityEngine.Random;
public class WorldBeyondManager : MonoBehaviour
{
static public WorldBeyondManager Instance = null;
[Header("Scene Preview")]
[SerializeField] private OVRSceneManager _sceneManager;
[SerializeField] private OVRPassthroughLayer _passthroughLayer;
bool _sceneModelLoaded = false;
float _floorHeight = 0.0f;
// after the Scene has been loaded successfuly, we still wait a frame before the data has "settled"
// e.g. VolumeAndPlaneSwitcher needs to happen first, and script execution order also isn't fixed by default
int _frameWait = 0;
[HideInInspector]
public OVRSceneAnchor[] _sceneAnchors;
[Header("Game Pieces")]
public VirtualPet _pet;
int _oppyDiscoveryCount = 0;
[HideInInspector]
public bool _oppyDiscovered = false;
public VirtualRoom _vrRoom;
public LightBeam _lightBeam;
Vector3 _toyBasePosition = Vector3.zero;
public Transform _finalUfoTarget;
public Transform _finalUfoRamp;
[HideInInspector]
public SpaceshipTrigger _spaceShipAnimator;
// Energy balls
Transform _ballContainer;
public GameObject _ballPrefab;
BallCollectable _hiddenBallCollectable = null;
Vector3 _hiddenBallPosition = Vector3.zero;
// the little gems spawned when a ball collides
List<BallDebris> _ballDebrisObjects;
const int _maxBallDebris = 100;
// How many balls the player currently has
[HideInInspector]
public int _ballCount = 0;
const int _startingBallCount = 0;
// How many balls Oppy should eat before heading to the UFO
// only starts incrementing during TheGreatBeyond chapter
public int _oppyTargetBallCount { private set; get; } = 2;
float _ballSpawnTimer = 0.0f;
const float _spawnTimeMin = 3.0f;
const float _spawnTimeMax = 6.0f;
bool _shouldSpawnBall = false;
public GameObject _worldShockwave;
public Material[] _environmentMaterials;
[Header("Overlays")]
public Camera _mainCamera;
public MeshRenderer _fadeSphere;
GameObject _backgroundFadeSphere;
public GameObject _titleScreenPrefab;
public GameObject _endScreenPrefab;
GameObject _titleScreen;
GameObject _endScreen;
float _vrRoomEffectTimer = 0.0f;
float _vrRoomEffectMaskTimer = 0.0f;
float _titleFadeTimer = 0.0f;
PassthroughStylist _passthroughStylist;
Color _cameraDark = new Color(0, 0, 0, 0.75f);
public enum GameChapter
{
Void, // waiting to find the Scene objects
Title, // the title screen
Introduction, // Passthrough fades in from black
OppyBaitsYou, // light beam is visible
SearchForOppy, // flashlight-hunting for Oppy & balls
OppyExploresReality,// Oppy walks around your room
TheGreatBeyond, // room walls come down
Ending // Oppy has collected all balls, flies away in ship
};
public GameChapter _currentChapter { get; private set; }
[Header("Hands")]
public OVRSkeleton _leftHand;
public OVRSkeleton _rightHand;
OVRHand _leftOVR;
OVRHand _rightOVR;
public Transform _leftHandAnchor;
public Transform _rightHandAnchor;
public OVRInput.Controller _gameController { get; private set; }
// hand input for grabbing is handled by the Interaction SDK
// otherwise, we track some basic custom poses (palm up/out, hand closed)
public bool _usingHands { get; private set; }
bool _handClosed = false;
public delegate void OnHand();
public OnHand OnHandOpenDelegate;
public OnHand OnHandClosedDelegate;
public OnHand OnHandDelegate;
[HideInInspector]
public float _fistValue = 0.0f;
public HandVisual _leftHandVisual;
public HandVisual _rightHandVisual;
public HandWristOffset _leftPointerOffset;
public HandWristOffset _rightPointerOffset;
public DistantInteractionLineVisual _interactionLineLeft;
public DistantInteractionLineVisual _interactionLineRight;
private float _leftHandGrabbedBallLastDistance = Mathf.Infinity;
private float _rightHandGrabbedBallLastDistance = Mathf.Infinity;
private void Awake()
{
if (!Instance)
{
Instance = this;
}
_currentChapter = GameChapter.Void;
_gameController = OVRInput.Controller.RTouch;
_fadeSphere.gameObject.SetActive(true);
_fadeSphere.sharedMaterial.SetColor("_Color", Color.black);
// copy the black fade sphere to be behind the intro title
// this shouldn't be necessary once color controls can be added to color PT
_backgroundFadeSphere = Instantiate(_fadeSphere.gameObject, _fadeSphere.transform.parent);
_usingHands = false;
_leftOVR = _leftHand.GetComponent<OVRHand>();
_rightOVR = _rightHand.GetComponent<OVRHand>();
_passthroughLayer.colorMapEditorType = OVRPassthroughLayer.ColorMapEditorType.None;
GameObject spawnedBalls = new GameObject("SpawnedBalls");
_ballContainer = spawnedBalls.transform;
_ballDebrisObjects = new List<BallDebris>();
_passthroughLayer.textureOpacity = 0;
_passthroughStylist = this.gameObject.AddComponent<PassthroughStylist>();
_passthroughStylist.Init(_passthroughLayer);
PassthroughStylist.PassthroughStyle darkPassthroughStyle = new PassthroughStylist.PassthroughStyle(
new Color(0, 0, 0, 0),
1.0f,
0.0f,
0.0f,
0.0f,
true,
Color.black,
Color.black,
Color.black);
_passthroughStylist.ForcePassthroughStyle(darkPassthroughStyle);
_spaceShipAnimator = _finalUfoTarget.GetComponent<SpaceshipTrigger>();
_titleScreen = Instantiate(_titleScreenPrefab);
_titleScreen.SetActive(false);
_endScreen = Instantiate(_endScreenPrefab);
// end screen needs to render above the black fade sphere, which is 4999
_endScreen.GetComponent<MeshRenderer>().sharedMaterial.renderQueue = 5000;
_endScreen.SetActive(false);
}
public void Start()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_ANDROID
OVRManager.eyeFovPremultipliedAlphaModeEnabled = false;
#endif
if (MultiToy.Instance) MultiToy.Instance.InitializeToys();
_pet.Initialize();
_sceneManager.SceneModelLoadedSuccessfully += SceneModelLoaded;
}
public void Update()
{
CalculateFistStrength();
if (_handClosed)
{
if (_fistValue < 0.2f)
{
_handClosed = false;
OnHandOpenDelegate?.Invoke();
}
else
{
OnHandDelegate?.Invoke();
}
}
else
{
if (_fistValue > 0.3f)
{
_handClosed = true;
OnHandClosedDelegate?.Invoke();
}
}
var usingHands = (
OVRInput.GetActiveController() == OVRInput.Controller.Hands ||
OVRInput.GetActiveController() == OVRInput.Controller.LHand ||
OVRInput.GetActiveController() == OVRInput.Controller.RHand ||
OVRInput.GetActiveController() == OVRInput.Controller.None);
if (usingHands != _usingHands)
{
_usingHands = usingHands;
if (usingHands)
{
if (_gameController == OVRInput.Controller.LTouch)
{
_gameController = OVRInput.Controller.LHand;
}
if (_gameController == OVRInput.Controller.RTouch)
{
_gameController = OVRInput.Controller.RHand;
}
}
else
{
if (_gameController == OVRInput.Controller.RHand)
{
_gameController = OVRInput.Controller.RTouch;
}
if (_gameController == OVRInput.Controller.LHand)
{
_gameController = OVRInput.Controller.LTouch;
}
}
MultiToy.Instance.UseHands(_usingHands, _gameController == OVRInput.Controller.RTouch);
MultiToy.Instance.EnableCollision(!_usingHands);
// update tutorial text when switching input, if onscreen
WorldBeyondTutorial.Instance.UpdateMessageTextForInput();
}
// constantly check if the player is within the polygonal floorplan of the room
if (_currentChapter >= GameChapter.Title)
{
if (!_vrRoom.IsPlayerInRoom())
{
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.ERROR_USER_WALKED_OUTSIDE_OF_ROOM);
}
else if (WorldBeyondTutorial.Instance._currentMessage == WorldBeyondTutorial.TutorialMessage.ERROR_USER_WALKED_OUTSIDE_OF_ROOM)
{
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.None);
}
}
// disable a hand if it's not tracked (avoiding ghost hands)
if (_leftOVR && _rightOVR)
{
_leftHandVisual.ForceOffVisibility = !_leftOVR.IsTracked;
_rightHandVisual.ForceOffVisibility = !_rightOVR.IsTracked;
}
switch (_currentChapter)
{
case GameChapter.Void:
if (_sceneModelLoaded) GetRoomFromScene();
break;
case GameChapter.Title:
PositionTitleScreens(false);
break;
case GameChapter.Introduction:
// Passthrough fading is done in the PlayIntroPassthrough coroutine
break;
case GameChapter.OppyBaitsYou:
// if either hand is getting close to the toy, grab it and start the experience
float handRange = 0.2f;
float leftRange = Vector3.Distance(OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch), MultiToy.Instance.transform.position);
float rightRange = Vector3.Distance(OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch), MultiToy.Instance.transform.position);
bool leftHandApproaching = leftRange <= handRange;
bool rightHandApproaching = rightRange <= handRange;
if (MultiToy.Instance._toyVisible && (leftHandApproaching || rightHandApproaching))
{
if (usingHands)
{
_gameController = leftRange < rightRange ? OVRInput.Controller.LHand : OVRInput.Controller.RHand;
MultiToy.Instance.SetToyMesh(MultiToy.ToyOption.None);
}
else
{
_gameController = leftRange < rightRange ? OVRInput.Controller.LTouch : OVRInput.Controller.RTouch;
MultiToy.Instance.ShowPassthroughGlove(true, _gameController == OVRInput.Controller.RTouch);
}
_usingHands = usingHands;
_lightBeam.CloseBeam();
MultiToy.Instance._grabToy_1.Play();
ForceChapter(GameChapter.SearchForOppy);
}
break;
case GameChapter.SearchForOppy:
break;
case GameChapter.OppyExploresReality:
break;
case GameChapter.TheGreatBeyond:
break;
case GameChapter.Ending:
if (_endScreen.activeSelf)
{
PositionTitleScreens(false);
}
break;
}
// make sure there's never a situation with no balls to grab
bool noHiddenBall = (_hiddenBallCollectable == null);
bool flashlightActive = MultiToy.Instance.IsFlashlightActive();
bool validMode = (_currentChapter > GameChapter.SearchForOppy && _currentChapter < GameChapter.Ending);
// note: this logic only executes after Oppy enters reality
// before that, the experience is scripted, so balls shouldn't spawn so randomly
if (flashlightActive && noHiddenBall && _oppyDiscoveryCount >= 2 && validMode)
{
_ballSpawnTimer -= Time.deltaTime;
if (_ballSpawnTimer <= 0.0f)
{
_shouldSpawnBall = true;
_ballSpawnTimer = Random.Range(_spawnTimeMin, _spawnTimeMax);
}
}
if (_shouldSpawnBall)
{
SpawnHiddenBall();
_shouldSpawnBall = false;
}
bool roomSparkleRingVisible = (_currentChapter >= GameChapter.OppyExploresReality && _hiddenBallCollectable);
roomSparkleRingVisible |= (_currentChapter == GameChapter.SearchForOppy && (_pet.gameObject.activeSelf || (_hiddenBallCollectable && !_hiddenBallCollectable._wasShot)));
Vector3 ripplePosition = _hiddenBallCollectable ? _hiddenBallPosition : Vector3.one * -1000.0f;
if (_currentChapter == GameChapter.SearchForOppy)
{
ripplePosition = _pet.gameObject.activeSelf ? _pet.transform.position : ripplePosition;
}
float effectSpeed = Time.deltaTime * 2.0f;
_vrRoomEffectTimer += roomSparkleRingVisible ? effectSpeed : -effectSpeed;
// to make balls easier to find, display a ripple effect on Passthrough
bool showRippleMask = _hiddenBallCollectable != null && flashlightActive && _hiddenBallCollectable._ballState == BallCollectable.BallStatus.Hidden;
_vrRoomEffectMaskTimer += showRippleMask ? effectSpeed : -effectSpeed;
if (_vrRoomEffectTimer >= 0.0f || _vrRoomEffectMaskTimer >= 0.0f)
{
VirtualRoom.Instance.SetWallEffectParams(ripplePosition, Mathf.Clamp01(_vrRoomEffectTimer), _vrRoomEffectMaskTimer);
}
_vrRoomEffectTimer = Mathf.Clamp01(_vrRoomEffectTimer);
_vrRoomEffectMaskTimer = Mathf.Clamp01(_vrRoomEffectMaskTimer);
if (_usingHands)
{
HideInvisibleHandAccessories();
}
}
/// <summary>
/// Calculates whether each hand should be visible or not
/// </summary>
private void HideInvisibleHandAccessories()
{
bool leftHandHidden = !_leftHand.IsDataValid || _leftHandVisual.ForceOffVisibility;
bool rightHandHidden = !_rightHand.IsDataValid || _rightHandVisual.ForceOffVisibility;
var grabbedBall = MultiToy.Instance._grabbedBall;
// Called before updating distance so that the hidden property is set while the ball is close to the hand
UpdateHandVisibility(leftHandHidden, _interactionLineLeft, _leftHandGrabbedBallLastDistance, _gameController == OVRInput.Controller.LHand, grabbedBall);
UpdateHandVisibility(rightHandHidden, _interactionLineRight, _rightHandGrabbedBallLastDistance, _gameController == OVRInput.Controller.RHand, grabbedBall);
// Hidden hands have a position of 0, only update if the hand is visible.
if (!leftHandHidden) _leftHandGrabbedBallLastDistance = grabbedBall ? Vector3.Distance(_leftHandAnchor.position, grabbedBall.transform.position): Mathf.Infinity;
if (!rightHandHidden) _rightHandGrabbedBallLastDistance = grabbedBall ? Vector3.Distance(_rightHandAnchor.position, grabbedBall.transform.position): Mathf.Infinity;
if (!_usingHands)
{
_interactionLineLeft.enabled = false;
_interactionLineRight.enabled = false;
}
}
/// <summary>
/// Hides the ball, reticule and tutorial if the hand is not tracked anymore.
/// Using previousHandToBallDistance to determine whether the current hand is holding the ball
/// </summary>
private void UpdateHandVisibility(bool handHidden, DistantInteractionLineVisual interactionLine, float previousHandToBallDistance, bool primary, [CanBeNull] BallCollectable grabbedBall)
{
bool holdingBall = grabbedBall != null && previousHandToBallDistance < 0.2f;
if (handHidden)
{
interactionLine.gameObject.SetActive(false);
if (primary) WorldBeyondTutorial.Instance.ForceInvisible();
if (holdingBall) grabbedBall.ForceInvisible();
}
else
{
interactionLine.gameObject.SetActive(_usingHands && MultiToy.Instance.GetCurrentToy() == MultiToy.ToyOption.Flashlight);
if (primary) WorldBeyondTutorial.Instance.ForceVisible();
if (holdingBall) grabbedBall.ForceVisible();
}
}
/// <summary>
/// Advance the story line of The World Beyond.
/// </summary>
public void ForceChapter(GameChapter forcedChapter)
{
StopAllCoroutines();
KillControllerVibration();
MultiToy.Instance.SetToy(forcedChapter);
_currentChapter = forcedChapter;
WorldBeyondEnvironment.Instance.ShowEnvironment((int)_currentChapter > (int)GameChapter.SearchForOppy);
if ((int)_currentChapter < (int)GameChapter.SearchForOppy) _mainCamera.backgroundColor = _cameraDark;
_pet.gameObject.SetActive((int)_currentChapter >= (int)GameChapter.OppyExploresReality);
_pet.SetOppyChapter(_currentChapter);
_pet.PlaySparkles(false);
if (_lightBeam) { _lightBeam.gameObject.SetActive(false); }
if (_titleScreen) _titleScreen.SetActive(false);
if (_endScreen) _endScreen.SetActive(false);
switch (_currentChapter)
{
case GameChapter.Title:
AudioManager.SetSnapshot_Title();
MusicManager.Instance.PlayMusic(MusicManager.Instance.IntroMusic);
StartCoroutine(ShowTitleScreen());
VirtualRoom.Instance.ShowAllWalls(false);
VirtualRoom.Instance.HideEffectMesh();
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.None);
WorldBeyondEnvironment.Instance._sun.enabled = false;
break;
case GameChapter.Introduction:
AudioManager.SetSnapshot_Introduction();
VirtualRoom.Instance.ShowDarkRoom(true);
VirtualRoom.Instance.AnimateEffectMesh();
StartCoroutine(PlayIntroPassthrough());
break;
case GameChapter.OppyBaitsYou:
_passthroughStylist.ResetPassthrough(0.1f);
StartCoroutine(PlaceToyRandomly(2.0f));
break;
case GameChapter.SearchForOppy:
VirtualRoom.Instance.HideEffectMesh();
_oppyDiscovered = false;
_oppyDiscoveryCount = 0;
_ballCount = _startingBallCount;
_passthroughStylist.ResetPassthrough(0.1f);
WorldBeyondEnvironment.Instance._sun.enabled = true;
StartCoroutine(CountdownToFlashlight(5.0f));
StartCoroutine(FlickerCameraToClearColor());
break;
case GameChapter.OppyExploresReality:
AudioManager.SetSnapshot_OppyExploresReality();
_passthroughStylist.ResetPassthrough(0.1f);
VirtualRoom.Instance.ShowAllWalls(true);
VirtualRoom.Instance.SetRoomSaturation(1.0f);
StartCoroutine(UnlockBallShooter(_usingHands ? 0f : 5.0f));
StartCoroutine(UnlockWallToy(_usingHands ? 5f : 20.0f));
_spaceShipAnimator.StartIdleSound(); // Start idle sound here - mix will mute it.
break;
case GameChapter.TheGreatBeyond:
AudioManager.SetSnapshot_TheGreatBeyond();
_passthroughStylist.ResetPassthrough(0.1f);
SetEnvironmentSaturation(IsGreyPassthrough() ? 0.0f : 1.0f);
if (IsGreyPassthrough()) StartCoroutine(SaturateEnvironmentColor());
MusicManager.Instance.PlayMusic(MusicManager.Instance.PortalOpen);
MusicManager.Instance.PlayMusic(MusicManager.Instance.TheGreatBeyondMusic);
break;
default:
break;
}
Debug.Log("TheWorldBeyond: started chapter " + _currentChapter);
}
/// <summary>
/// After the title screen fades to black, start the transition from black to darkened-Passthrough.
/// After that, trigger the next chapter that shows the light beam.
/// </summary>
IEnumerator PlayIntroPassthrough()
{
_backgroundFadeSphere.SetActive(false);
// first, make everything black
PassthroughStylist.PassthroughStyle darkPassthroughStyle = new PassthroughStylist.PassthroughStyle(
new Color(0, 0, 0, 0),
1.0f,
0.0f,
0.0f,
0.0f,
true,
Color.black,
Color.black,
Color.black);
_passthroughStylist.ForcePassthroughStyle(darkPassthroughStyle);
// fade in edges
float timer = 0.0f;
float lerpTime = 4.0f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
Color edgeColor = Color.white;
edgeColor.a = Mathf.Clamp01(timer / 3.0f); // fade from transparent
_passthroughLayer.edgeColor = edgeColor;
float normTime = Mathf.Clamp01(timer / lerpTime);
_fadeSphere.sharedMaterial.SetColor("_Color", Color.Lerp(Color.black, Color.clear, normTime));
VirtualRoom.Instance.SetEdgeEffectIntensity(normTime);
// once lerpTime is over, fade in normal passthrough
if (timer >= lerpTime)
{
PassthroughStylist.PassthroughStyle normalPassthrough = new PassthroughStylist.PassthroughStyle(
new Color(0, 0, 0, 0),
1.0f,
0.0f,
0.0f,
0.0f,
false,
Color.white,
Color.black,
Color.white);
_passthroughStylist.ShowStylizedPassthrough(normalPassthrough, 5.0f);
_fadeSphere.gameObject.SetActive(false);
}
yield return null;
}
yield return new WaitForSeconds(3.0f);
ForceChapter(GameChapter.OppyBaitsYou);
}
/// <summary>
/// When you first grab the MultiToy, the world flashes for a split second.
/// </summary>
IEnumerator FlickerCameraToClearColor()
{
float timer = 0.0f;
float flickerTimer = 0.5f;
while (timer <= flickerTimer)
{
timer += Time.deltaTime;
float normTimer = Mathf.Clamp01(0.5f * timer / flickerTimer);
_mainCamera.backgroundColor = Color.Lerp(Color.black, _cameraDark, MultiToy.Instance.EvaluateFlickerCurve(normTimer));
if (timer >= flickerTimer)
{
VirtualRoom.Instance.ShowAllWalls(true);
VirtualRoom.Instance.ShowDarkRoom(false);
VirtualRoom.Instance.SetRoomSaturation(IsGreyPassthrough() ? 0 : 1);
WorldBeyondEnvironment.Instance.ShowEnvironment(true);
}
yield return null;
}
}
/// <summary>
/// Handle black fading, Passthrough blending, and the intro title screen animation.
/// </summary>
IEnumerator ShowTitleScreen()
{
_fadeSphere.gameObject.SetActive(true);
_backgroundFadeSphere.gameObject.SetActive(true);
PassthroughStylist.PassthroughStyle darkPassthroughStyle = new PassthroughStylist.PassthroughStyle(
new Color(0, 0, 0, 0),
1.0f,
0.0f,
0.0f,
0.0f,
true,
Color.black,
Color.black,
Color.black);
_passthroughStylist.ForcePassthroughStyle(darkPassthroughStyle);
_fadeSphere.sharedMaterial.SetColor("_Color", Color.black);
_fadeSphere.sharedMaterial.renderQueue = 4999;
_backgroundFadeSphere.GetComponent<MeshRenderer>().material.renderQueue = 1997;
_backgroundFadeSphere.GetComponent<MeshRenderer>().material.SetColor("_Color", Color.black);
_titleScreen.SetActive(true);
PositionTitleScreens(true);
// fade/animate title text
float timer = 0.0f;
float lerpTime = 8.0f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
float normTimer = Mathf.Clamp01(timer /lerpTime);
// fade black above everything
float blackFade = Mathf.Clamp01(normTimer * 5) * Mathf.Clamp01((1 - normTimer) * 5);
_fadeSphere.sharedMaterial.SetColor("_Color", Color.Lerp(Color.black, Color.clear, blackFade));
// once lerpTime is over, fade in normal passthrough
if (timer >= lerpTime)
{
_titleScreen.SetActive(false);
}
yield return null;
}
ForceChapter(GameChapter.Introduction);
}
/// <summary>
/// When Oppy first enters reality, prepare to unlock the ball shooter.
/// </summary>
IEnumerator UnlockBallShooter(float countdown)
{
yield return new WaitForSeconds(countdown);
// ensures the flashlight works again, once it's switched back to
MultiToy.Instance.SetFlickerTime(0.0f);
MultiToy.Instance.UnlockBallShooter();
OVRInput.SetControllerVibration(1, 1, _gameController);
yield return new WaitForSeconds(1.0f);
KillControllerVibration();
}
/// <summary>
/// After a few seconds of playing with Oppy, unlock the wall toggler toy.
/// </summary>
IEnumerator UnlockWallToy(float countdown)
{
yield return new WaitForSeconds(countdown);
MultiToy.Instance.UnlockWallToy();
OVRInput.SetControllerVibration(1, 1, _gameController);
yield return new WaitForSeconds(1.0f);
KillControllerVibration();
}
/// <summary>
/// Prepare the toy and light beam for their initial appearance.
/// </summary>
IEnumerator PlaceToyRandomly(float spawnTime)
{
yield return new WaitForSeconds(spawnTime);
MultiToy.Instance.ShowToy(true);
MultiToy.Instance.SetToyMesh(MultiToy.ToyOption.Flashlight);
_toyBasePosition = GetRandomToyPosition();
_lightBeam.gameObject.SetActive(true);
_lightBeam.transform.localScale = new Vector3(1, VirtualRoom.Instance.GetCeilingHeight(), 1);
_lightBeam.Prepare(_toyBasePosition);
}
/// <summary>
/// Right after player grabs Multitoy, wait a few seconds before turning on the flashlight.
/// </summary>
IEnumerator CountdownToFlashlight(float spawnTime)
{
yield return new WaitForSeconds(spawnTime - 0.5f);
OVRInput.SetControllerVibration(1, 1, _gameController);
MultiToy.Instance.EnableFlashlightCone(true);
if (_usingHands)
{
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.EnableFlashlight);
}
MultiToy.Instance._flashlightFlicker_1.Play();
float timer = 0.0f;
float lerpTime = 0.5f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
MultiToy.Instance.SetFlickerTime((0.5f * timer / lerpTime) + 0.5f);
if (timer >= lerpTime)
{
MultiToy.Instance.SetFlickerTime(1.0f);
}
yield return null;
}
KillControllerVibration();
StartCoroutine(SpawnPetRandomly(true, Random.Range(_spawnTimeMin, _spawnTimeMax)));
}
/// <summary>
/// Called from OVRSceneManager.SceneModelLoadedSuccessfully().
/// This only sets a flag, and the game behavior begins in Update().
/// This is because OVRSceneManager does all the heavy lifting, and this experience requires it to be complete.
/// </summary>
void SceneModelLoaded()
{
_sceneModelLoaded = true;
}
/// <summary>
/// When the Scene has loaded, instantiate all the wall and furniture items.
/// OVRSceneManager creates proxy anchors, that we use as parent tranforms for these instantiated items.
/// </summary>
void GetRoomFromScene()
{
if (_frameWait < 1)
{
_frameWait++;
return;
}
try
{
// OVRSceneAnchors have already been instantiated from OVRSceneManager
// to avoid script execution conflicts, we do this once in the Update loop instead of directly when the SceneModelLoaded event is fired
_sceneAnchors = FindObjectsOfType<OVRSceneAnchor>();
// WARNING: right now, a Scene is guaranteed to have closed walls
// if this ever changes, this logic needs to be revisited because the whole game fails (e.g. furniture with no walls)
_vrRoom.Initialize(_sceneAnchors);
// even though loading has succeeded to this point, do some sanity checks
if (!_vrRoom.IsPlayerInRoom())
{
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.ERROR_USER_STARTED_OUTSIDE_OF_ROOM);
}
WorldBeyondEnvironment.Instance.Initialize();
ForceChapter(GameChapter.Title);
}
catch
{
// if initialization messes up for some reason, quit the app
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.ERROR_NO_SCENE_DATA);
}
}
/// <summary>
/// When the flashlight shines on an energy ball, advance the story and handle the UI message.
/// </summary>
public void DiscoveredBall(BallCollectable collected)
{
if (!_usingHands) // Balls are not absorbed, just picked up when using hands
{
_ballCount++;
}
WorldBeyondTutorial.Instance.HideMessage(WorldBeyondTutorial.TutorialMessage.BallSearch);
WorldBeyondTutorial.Instance.HideMessage(WorldBeyondTutorial.TutorialMessage.NoBalls);
// when using hands, make sure the discovered ball was actually hidden
// otherwise, grabbing any ball will advance the script in undesirable ways
if (_usingHands && collected._wasShot)
{
return;
}
if (_currentChapter == GameChapter.SearchForOppy)
{
// in case we already picked up a ball and triggered the coroutine, cancel the old one
// this is only a problem when using hands, since the balls stay around
if (_usingHands)
{
StopAllCoroutines();
}
StartCoroutine(SpawnPetRandomly(false, Random.Range(_spawnTimeMin, _spawnTimeMax)));
}
}
/// <summary>
/// Get the closest ball to Oppy that's available to be eaten. (some are intentionally unavailable, like hidden ones)
/// </summary>
public BallCollectable GetClosestEdibleBall(Vector3 petPosition)
{
float closestDist = 20.0f;
BallCollectable closestBall = null;
foreach (Transform bcXform in _ballContainer)
{
BallCollectable bc = bcXform.GetComponent<BallCollectable>();
if (!bc)
{
continue;
}
float thisDist = Vector3.Distance(petPosition, bc.gameObject.transform.position);
if (thisDist < closestDist
&& bc._ballState == BallCollectable.BallStatus.Released
&& bc._shotTimer >= 1.0f)
{
closestDist = thisDist;
closestBall = bc;
}
}
return closestBall;
}
/// <summary>
/// Simple cone to find the best candidate ball within view of the flashlight
/// </summary>
public BallCollectable GetTargetedBall(Vector3 toyPos, Vector3 toyFwd)
{
float closestAngle = 0.9f;
BallCollectable closestBall = null;
for (int i = 0; i < _ballContainer.childCount; i++)
{
BallCollectable bc = _ballContainer.GetChild(i).GetComponent<BallCollectable>();
if (!bc)
{
continue;
}
Vector3 rayFromHand = (bc.gameObject.transform.position - toyPos).normalized;
float thisViewAngle = Vector3.Dot(rayFromHand, toyFwd);
if (thisViewAngle > closestAngle)
{
if (bc._ballState == BallCollectable.BallStatus.Available ||
bc._ballState == BallCollectable.BallStatus.Hidden ||
bc._ballState == BallCollectable.BallStatus.Released)
{
closestAngle = thisViewAngle;
closestBall = bc;
}
}
}
return closestBall;
}
/// <summary>
/// When discovering Oppy for the last time, the flashlight dies temporarily as she "pops" into reality.
/// </summary>
IEnumerator MalfunctionFlashlight()
{
yield return new WaitForSeconds(2.0f);
GameObject effectRing = Instantiate(_worldShockwave);
effectRing.transform.position = _pet.transform.position;
effectRing.GetComponent<ParticleSystem>().Play();
_pet.EnablePassthroughShell(true);
PassthroughStylist.PassthroughStyle weirdPassthrough = new PassthroughStylist.PassthroughStyle(
new Color(0, 0, 0, 0),
1.0f,
0.0f,
0.0f,
0.8f,
true,
new Color(0,0.5f,1,0.5f),
Color.black,
Color.white);
_passthroughStylist.ShowStylizedPassthrough(weirdPassthrough, 0.2f);
WorldBeyondEnvironment.Instance.FlickerSun();
// flicker out
MultiToy.Instance._flashlightFlicker_1.Play();
float timer = 0.0f;
float lerpTime = 0.3f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
MultiToy.Instance.SetFlickerTime(0.5f * timer / lerpTime);
if (timer >= lerpTime)
{
MultiToy.Instance.SetFlickerTime(0.5f);
MultiToy.Instance.StopLoopingSound();
MultiToy.Instance._malfunction_1.Play();
_passthroughStylist.ResetPassthrough(0.15f);
}
yield return null;
}
ForceChapter(GameChapter.OppyExploresReality);
_pet.EndLookTarget();
}
/// <summary>
/// After shining the flashlight on Oppy the first two times, it flickers so she can disappear.
/// </summary>
IEnumerator FlickerFlashlight(float delayTime = 0.0f)
{
yield return new WaitForSeconds(delayTime);
// flicker out
MultiToy.Instance._flashlightFlicker_1.Play();
MultiToy.Instance._flashlightLoop_1.Pause();
float timer = 0.0f;
float lerpTime = 0.2f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
MultiToy.Instance.SetFlickerTime(0.5f * timer / lerpTime);
if (timer >= lerpTime)
{
MultiToy.Instance.SetFlickerTime(0.5f);
}
yield return null;
}
// play Oppy teleport particles, only on the middle discovery
if (_oppyDiscoveryCount == 1)
{
_pet.PlayTeleport();
}
// hide Oppy
_oppyDiscovered = false;
_oppyDiscoveryCount++;
_pet.ResetAnimFlags();
float colorSaturation = IsGreyPassthrough() ? Mathf.Clamp01(_oppyDiscoveryCount / 3.0f) : 1.0f;
_pet.SetMaterialSaturation(colorSaturation);
_pet.StartLookTarget();
_pet.gameObject.SetActive(false);
// increase room saturation while flashlight is off
VirtualRoom.Instance.SetRoomSaturation(colorSaturation);
// flicker in
timer = 0.0f;
while (timer <= lerpTime)
{
timer += Time.deltaTime;
MultiToy.Instance.SetFlickerTime((0.5f * timer / lerpTime) + 0.5f);
if (timer >= lerpTime)
{
MultiToy.Instance.SetFlickerTime(1.0f);
}
yield return null;
}
MultiToy.Instance._flashlightLoop_1.Resume();
if (_oppyDiscoveryCount == 1)
{
WorldBeyondTutorial.Instance.DisplayMessage(WorldBeyondTutorial.TutorialMessage.BallSearch);
_hiddenBallCollectable.SetState(BallCollectable.BallStatus.Hidden);
}
else
{
// spawn ball only after the first discovery (first ball already exists)
yield return new WaitForSeconds(Random.Range(_spawnTimeMin, _spawnTimeMax));
SpawnHiddenBall();
}
}
/// <summary>
/// During the discovery chapter, Oppy is place in hidden locations in the space.
/// </summary>
IEnumerator SpawnPetRandomly(bool firstTimeSpawning, float waitTime)
{
yield return new WaitForSeconds(waitTime);
// because the pet has a Navigation component, we must turn off the object before manually moving
// this is to avoid the pet getting "stuck" on the walls
_pet.gameObject.SetActive(false);
Vector3 spawnPos = GetRandomPetPosition();
Vector3 fwd = _mainCamera.transform.position - spawnPos;
Quaternion oppyRotation = Quaternion.LookRotation(new Vector3(fwd.x, 0, fwd.z));
_pet.transform.rotation = oppyRotation;
_pet.transform.position = spawnPos - _pet.transform.right * 0.1f;
_pet.gameObject.SetActive(true);
_pet.PlaySparkles(true);
_pet.SetLookDirection(fwd.normalized);
if (firstTimeSpawning)
{
_pet.PrepareInitialDiscoveryAnim();
_pet.SetMaterialSaturation(IsGreyPassthrough() ? 0.0f : 1.0f);
GameObject hiddenBall = Instantiate(_ballPrefab);
_hiddenBallCollectable = hiddenBall.GetComponent<BallCollectable>();
_hiddenBallPosition = spawnPos + _pet.transform.right * 0.05f + Vector3.up * 0.06f;
_hiddenBallCollectable.PlaceHiddenBall(_hiddenBallPosition, 0);
_hiddenBallCollectable.SetState(BallCollectable.BallStatus.Unavailable);
}
}
/// <summary>
/// When the player has the flashlight active, there should always be a hidden ball to discover.
/// </summary>
void SpawnHiddenBall()
{
// if spawning on a wall, track the id:
// if the wall is toggled off, we need to destroy the ball
int wallID = -1;
GameObject hiddenBall = Instantiate(_ballPrefab);
_hiddenBallCollectable = hiddenBall.GetComponent<BallCollectable>();
_hiddenBallPosition = GetRandomBallPosition(ref wallID);
_hiddenBallCollectable.PlaceHiddenBall(_hiddenBallPosition, wallID);
}