ProximityActivate.cs
2.48 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProximityActivate : MonoBehaviour
{
public Transform distanceActivator, lookAtActivator;
public float distance;
public Transform activator;
public bool activeState = false;
public CanvasGroup target;
public bool lookAtCamera = true;
public bool enableInfoPanel = false;
public GameObject infoIcon;
float alpha;
public CanvasGroup infoPanel;
Quaternion originRotation, targetRotation;
void Start()
{
originRotation = transform.rotation;
alpha = activeState ? 1 : -1;
if (activator == null) activator = Camera.main.transform;
infoIcon.SetActive(infoPanel != null);
}
bool IsTargetNear()
{
var distanceDelta = distanceActivator.position - activator.position;
if (distanceDelta.sqrMagnitude < distance * distance)
{
if (lookAtActivator != null)
{
var lookAtActivatorDelta = lookAtActivator.position - activator.position;
if (Vector3.Dot(activator.forward, lookAtActivatorDelta.normalized) > 0.95f)
return true;
}
var lookAtDelta = target.transform.position - activator.position;
if (Vector3.Dot(activator.forward, lookAtDelta.normalized) > 0.95f)
return true;
}
return false;
}
void Update()
{
if (!activeState)
{
if (IsTargetNear())
{
alpha = 1;
activeState = true;
}
}
else
{
if (!IsTargetNear())
{
alpha = -1;
activeState = false;
enableInfoPanel = false;
}
}
target.alpha = Mathf.Clamp01(target.alpha + alpha * Time.deltaTime);
if (infoPanel != null)
{
if (Input.GetKeyDown(KeyCode.Space))
enableInfoPanel = !enableInfoPanel;
infoPanel.alpha = Mathf.Lerp(infoPanel.alpha, Mathf.Clamp01(enableInfoPanel ? alpha : 0), Time.deltaTime * 10);
}
if (lookAtCamera)
{
if (activeState)
targetRotation = Quaternion.LookRotation(activator.position - transform.position);
else
targetRotation = originRotation;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime);
}
}
}