AR + GPS Location  3.0.0
All Classes Namespaces Functions Variables Properties Events Pages
SmoothMove.cs
1 using System;
2 using System.Collections;
3 using UnityEngine;
4 
5 namespace ARLocation.Utils
6 {
7  public class SmoothMove : MonoBehaviour
8  {
9  public enum Mode
10  {
11  Horizontal,
12  Full
13  }
14 
15  [Tooltip("The smoothing factor."), Range(0, 1)]
16  public float Epsilon = 0.5f;
17 
18  [Tooltip("The Precision."), Range(0, 0.1f)]
19  public float Precision = 0.05f;
20 
21  public Vector3 Target
22  {
23  get { return target; }
24  set
25  {
26  target = value;
27 
28  if (co != null)
29  {
30  StopCoroutine(co);
31  }
32 
33  co = MoveTo(target);
34  StartCoroutine(MoveTo(target));
35  }
36  }
37 
38  [Tooltip("The mode. If set to 'Horizontal', will leave the y component unchanged. Full means the object will move in all 3D coordinates.")]
39  public Mode SmoothMoveMode = Mode.Full;
40 
41  private Vector3 target;
42  private Action onTargetReached;
43  private IEnumerator co;
44 
45  public void Move(Vector3 to, Action callback = null)
46  {
47  onTargetReached = callback;
48 
49  Target = to;
50  }
51 
52  private IEnumerator MoveTo(Vector3 pTarget)
53  {
54  if (SmoothMoveMode == Mode.Horizontal)
55  {
56 
57 
58  Vector2 horizontalPosition = MathUtils.HorizontalVector(transform.position);
59  Vector2 horizontalTarget = MathUtils.HorizontalVector(pTarget);
60 
61  while (Vector2.Distance(horizontalPosition, horizontalTarget) > Precision)
62  {
63  float t = 1.0f - Mathf.Pow(Epsilon, Time.deltaTime);
64  horizontalPosition = Vector3.Lerp(horizontalPosition, horizontalTarget, t);
65 
66  transform.position = MathUtils.HorizontalVectorToVector3(horizontalPosition, transform.position.y);
67 
68  yield return null;
69  }
70 
71  transform.position = MathUtils.HorizontalVectorToVector3(horizontalTarget, transform.position.y);
72 
73  onTargetReached?.Invoke();
74  onTargetReached = null;
75  }
76  else
77  {
78  while (Vector3.Distance(transform.position, pTarget) > Precision)
79  {
80  float t = 1.0f - Mathf.Pow(Epsilon, Time.deltaTime);
81  transform.position = Vector3.Lerp(transform.position, pTarget, t);
82 
83  yield return null;
84  }
85 
86  transform.position = pTarget;
87 
88  onTargetReached?.Invoke();
89  onTargetReached = null;
90  }
91  }
92 
93  public static SmoothMove AddSmoothMove(GameObject go, float epsilon)
94  {
95  var smoothMove = go.AddComponent<SmoothMove>();
96  smoothMove.Epsilon = epsilon;
97 
98  return smoothMove;
99  }
100  }
101 }
ARLocation.Utils
Definition: CreatePointOfInterestTextMeshes.cs:9
ARLocation.Utils.SmoothMove
Definition: SmoothMove.cs:8