-
Notifications
You must be signed in to change notification settings - Fork 0
/
LookAtPlayer.cs
58 lines (47 loc) · 2.03 KB
/
LookAtPlayer.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
using System;
using UnityEngine;
namespace BandTogether;
public class LookAtPlayer : MonoBehaviour
{
[SerializeField] CharacterDialogueTree characterDialogueTree;
[SerializeField] Transform idleTarget;
[SerializeField] Transform neckBone;
[SerializeField] bool isGhird;
private bool _lookAtPlayer = false;
private void FixedUpdate()
{
var npcTransform = transform;
var relativePlayerPosition = Locator._playerBody.GetPosition() - npcTransform.position;
var playerInRange = relativePlayerPosition.sqrMagnitude < 16;
if (!playerInRange)
{
_lookAtPlayer = false;
return;
}
_lookAtPlayer = Vector3.Angle(npcTransform.forward, Vector3.ProjectOnPlane(relativePlayerPosition, npcTransform.up)) < 90;
}
private void Update()
{
// ModMain.Instance.ModHelper.Console.WriteLine("In convo: " + _CharacterDialogueTree);
var targetPosition = _lookAtPlayer
? Locator.GetActiveCamera().transform.position
: idleTarget.position;
var targetLookDir = (targetPosition - neckBone.position).normalized;
Vector3 currentLookDir = isGhird ? -neckBone.up : neckBone.up;
if ((targetLookDir - currentLookDir).sqrMagnitude < 0.001) return;
var nextLookForward = Vector3.Lerp(currentLookDir, targetLookDir, Time.deltaTime);
if (isGhird)
{
var nextLookUp = Vector3.Cross(nextLookForward, neckBone.parent.forward);
var nextLookLeft = Vector3.Cross(nextLookUp, nextLookForward);
neckBone.LookAt(neckBone.position + nextLookLeft, -nextLookForward);
}
else
{
var nextLookUp = Vector3.Cross(nextLookForward, -neckBone.parent.right);
// because of the orientation of the bones, we actually need to look at
// the up vector with up being the direction we actually look
neckBone.LookAt(neckBone.position + nextLookUp, nextLookForward);
}
}
}