-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsmoothLookAt.cs
More file actions
105 lines (84 loc) · 3.37 KB
/
smoothLookAt.cs
File metadata and controls
105 lines (84 loc) · 3.37 KB
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
using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityTransform
{
[TaskCategory("Basic/Transform")]
[TaskDescription("Smoothly looks at a game object or position.")]
public class smoothLookAt : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject basegameObject;
public SharedGameObject targetObject;
public SharedVector3 targetPosition;
public SharedBool keepVertical;
public SharedVector3 upVector;
private SharedGameObject previousGo;
private SharedQuaternion lastRotation;
private SharedQuaternion desiredRotation;
public SharedFloat speed;
public SharedFloat finishTolerance;
[Tooltip(" if this is NOT checked the task will keep running and not return success.")]
public SharedBool successOnFinish;
private Transform targetTransform;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(basegameObject.Value);
if (currentGameObject != prevGameObject)
{
targetTransform = currentGameObject.GetComponent<Transform>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
var go = basegameObject.Value.gameObject;
var goTarget = targetObject.Value;
if (previousGo.Value != go)
{
lastRotation = go.transform.rotation;
desiredRotation = lastRotation;
previousGo = go;
}
// desired look at position
Vector3 lookAtPos;
if (goTarget != null)
{
lookAtPos = !targetPosition.IsNone ?
goTarget.transform.TransformPoint(targetPosition.Value) :
goTarget.transform.position;
} else
{
lookAtPos = targetPosition.Value;
}
if (keepVertical.Value)
{
lookAtPos.y = go.transform.position.y;
}
// smooth look at
var diff = lookAtPos - go.transform.position;
if (diff != Vector3.zero && diff.sqrMagnitude > 0)
{
desiredRotation = Quaternion.LookRotation(diff, upVector.IsNone ? Vector3.up : upVector.Value);
}
lastRotation = Quaternion.Slerp(lastRotation.Value, desiredRotation.Value, speed.Value * Time.deltaTime);
go.transform.rotation = lastRotation.Value;
// send finish event?
if (successOnFinish.Value == true)
{
var targetDir = lookAtPos - go.transform.position;
var angle = Vector3.Angle(targetDir, go.transform.forward);
if (Mathf.Abs(angle) <= finishTolerance.Value)
{
return TaskStatus.Success;
}
}
return TaskStatus.Running;
}
public override void OnReset()
{
basegameObject = null;
speed = 5;
finishTolerance = 1;
}
}
}