Tanoda
SimpleFacingCameraCallbacks.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System.Collections;
10using System.Collections.Generic;
11using UnityEngine;
13
14namespace Leap.Unity.Examples {
15
16 [AddComponentMenu("")]
17 public class SimpleFacingCameraCallbacks : MonoBehaviour {
18
19 public Transform toFaceCamera;
20 public Camera cameraToFace;
21
22 private bool _initialized = false;
23 private bool _isFacingCamera = false;
24
25 public UnityEvent OnBeginFacingCamera;
26 public UnityEvent OnEndFacingCamera;
27
28 void Start() {
29 if (toFaceCamera != null) initialize();
30 }
31
32 private void initialize() {
33 if(cameraToFace == null) { cameraToFace = Camera.main; }
34 // Set "_isFacingCamera" to be whatever the current state ISN'T, so that we are
35 // guaranteed to fire a UnityEvent on the first initialized Update().
36 _isFacingCamera = !GetIsFacingCamera(toFaceCamera, cameraToFace);
37 _initialized = true;
38 }
39
40 void Update() {
41 if (toFaceCamera != null && !_initialized) {
42 initialize();
43 }
44 if (!_initialized) return;
45
46 if (GetIsFacingCamera(toFaceCamera, cameraToFace, _isFacingCamera ? 0.77F : 0.82F) != _isFacingCamera) {
47 _isFacingCamera = !_isFacingCamera;
48
49 if (_isFacingCamera) {
50 OnBeginFacingCamera.Invoke();
51 }
52 else {
53 OnEndFacingCamera.Invoke();
54 }
55 }
56 }
57
58 public static bool GetIsFacingCamera(Transform facingTransform, Camera camera, float minAllowedDotProduct = 0.8F) {
59 return Vector3.Dot((camera.transform.position - facingTransform.position).normalized, facingTransform.forward) > minAllowedDotProduct;
60 }
61
62 }
63
64}
static bool GetIsFacingCamera(Transform facingTransform, Camera camera, float minAllowedDotProduct=0.8F)