using NextMind.Examples.Steps;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace NextMind.Examples.Discovery
{
///
/// Implementation of an managed by the .
/// During this step, the user learn the usage of the OnTriggered NeuroTags actions.
///
public class PersistantToggleStep : AbstractStep
{
///
/// The spot light reacting to the NeuroTag's trigger.
///
[SerializeField]
private GameObject spotLight = null;
///
/// The animator attached to the NeuroTag
///
[SerializeField]
private Animator toggleAnimator = null;
///
/// The image component of the toggle's knob.
///
[SerializeField]
private Image knob = null;
///
/// The color to apply on the nob when untoggled.
///
[SerializeField]
private Color knobOffColor = Color.grey;
///
/// The color to apply on the nob when toggled.
///
[SerializeField]
private Color knobOnColor = Color.green;
private bool triggered = false;
private float triggerTime = 0;
#region AbstractStep implementation
public override void OnEnterStep()
{
// Dim the lights when entering the step, to better see the action on the lights.
StartCoroutine(HubManager.Instance.SetLights(false));
spotLight.SetActive(false);
// Ensure having the toggle turned off.
triggered = false;
Toggle(false,true);
}
public override void OnExitStep()
{
var hubManager = HubManager.Instance;
if (hubManager != null)
{
// Set the lights intensities back to their original values.
HubManager.Instance.StartCoroutine(HubManager.Instance.SetLights(true));
}
}
#endregion
#region NeuroTag events
///
/// Function triggered when user focus on the toggle.
///
public void OnTriggered()
{
Toggle(!triggered);
triggerTime = Time.time;
}
///
/// Function triggered when user maintain the focus on the toggle.
///
public void OnMaintained()
{
// If the user maintained his focus for more than 4 seconds, toggle the button again.
if (Time.time - triggerTime > 4)
{
OnTriggered();
}
}
#endregion
///
/// Set the state of the toggle.
///
///
/// If true, skip the animation
private void Toggle(bool toggled, bool instant=false)
{
triggered = toggled;
// Animate the knob.
toggleAnimator.SetBool("Toggled", triggered);
if (instant)
{
toggleAnimator.Play("SwitchOff", 0, 1);
knob.material.color = triggered ? knobOnColor : knobOffColor;
}
else
{
// Change the color.
StartCoroutine(SwitchColor(triggered ? knobOnColor : knobOffColor));
}
// Set the spotlight on/off regarding the toggle value.
spotLight.SetActive(triggered);
}
///
/// Smoothly change the color of toggle's knob.
///
/// The targeted color
private IEnumerator SwitchColor(Color targetColor)
{
float t = 0;
float currentTime = 0f;
float duration = 0.5f;
Color startColor = knob.material.color;
while (t < 1)
{
Color c = Color.Lerp(startColor, targetColor, t);
knob.material.color = c;
currentTime += Time.deltaTime;
t = currentTime / duration;
yield return null;
}
knob.material.color = targetColor;
}
}
}