-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathHandleAnimationMotif.cs
92 lines (76 loc) · 2.91 KB
/
HandleAnimationMotif.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
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
using System.Collections;
using Oculus.Interaction;
using UnityEngine;
namespace MRMotifs.SharedActivities.Helpers
{
/// <summary>
/// Manages scaling and alpha transitions for an object over time, using a coroutine to animate the object smoothly.
/// </summary>
public class HandleAnimationMotif : MonoBehaviour
{
[Tooltip("Interactable Unity Event Wrapper to call the animation methods from.")]
[SerializeField]
private InteractableUnityEventWrapper interactableUnityEventWrapper;
[Tooltip("The target scale of the object when scaling up.")]
[SerializeField]
private Vector3 targetScale = new(0.03f, 0.25f, 0.03f);
[Tooltip("The duration (in seconds) it takes to scale the object.")]
[SerializeField]
private float scalingDuration = 0.5f;
[Tooltip("The material used to modify the object's alpha transparency.")]
[SerializeField]
private Material material;
private Vector3 m_initialScale;
private Coroutine m_currentCoroutine;
private void Awake()
{
m_initialScale = transform.localScale;
interactableUnityEventWrapper.WhenHover.AddListener(ScaleUp);
interactableUnityEventWrapper.WhenUnhover.AddListener(ScaleDown);
}
private void OnDestroy()
{
interactableUnityEventWrapper.WhenHover.RemoveListener(ScaleUp);
interactableUnityEventWrapper.WhenUnhover.RemoveListener(ScaleDown);
}
private void ScaleUp()
{
if (m_currentCoroutine != null)
{
StopCoroutine(m_currentCoroutine);
}
m_currentCoroutine = StartCoroutine(ScaleObject(targetScale, 180));
}
private void ScaleDown()
{
if (m_currentCoroutine != null)
{
StopCoroutine(m_currentCoroutine);
}
m_currentCoroutine = StartCoroutine(ScaleObject(m_initialScale, 0));
}
private IEnumerator ScaleObject(Vector3 target, float targetAlpha)
{
var startScale = transform.localScale;
var startAlpha = material.color.a * 255f;
float timeElapsed = 0;
while (timeElapsed < scalingDuration)
{
var t = timeElapsed / scalingDuration;
transform.localScale = Vector3.Lerp(startScale, target, t);
SetMaterialAlpha(Mathf.Lerp(startAlpha, targetAlpha, t));
timeElapsed += Time.deltaTime;
yield return null;
}
transform.localScale = target;
SetMaterialAlpha(targetAlpha);
}
private void SetMaterialAlpha(float alpha)
{
var color = material.color;
color.a = alpha / 255f;
material.color = color;
}
}
}