/// ---------------------------------------------
/// Ultimate Character Controller
/// Copyright (c) Opsive. All Rights Reserved.
/// https://www.opsive.com
/// ---------------------------------------------
namespace Opsive.UltimateCharacterController.Input.VirtualControls
{
using UnityEngine;
using UnityEngine.EventSystems;
///
/// A virtual control that the player can press.
///
public class VirtualButton : VirtualControl, IPointerDownHandler, IPointerUpHandler
{
[Tooltip("The name of the input.")]
[SerializeField] protected string m_ButtonName;
private bool m_Pressed;
private int m_Frame;
///
/// Initialize the default values.
///
protected override void Awake()
{
if (string.IsNullOrEmpty(m_ButtonName)) {
Debug.LogError("Error: The virtual button " + gameObject.name + " cannot have an empty input name.");
return;
}
base.Awake();
if (m_VirtualControlsManager != null) {
m_VirtualControlsManager.RegisterVirtualControl(m_ButtonName, this);
}
}
///
/// Callback when a pointer has pressed on the button.
///
/// The pointer data.
public void OnPointerDown(PointerEventData data)
{
if (m_Pressed) {
return;
}
m_Pressed = true;
m_Frame = Time.frameCount;
}
///
/// Callback when a finger has released the button.
///
/// The pointer data.
public void OnPointerUp(PointerEventData data)
{
if (!m_Pressed) {
return;
}
m_Pressed = false;
m_Frame = Time.frameCount;
}
///
/// Returns if the button is true with the specified ButtonAction.
///
/// The type of action to check.
/// The status of the action.
public override bool GetButton(InputBase.ButtonAction action)
{
if (action == InputBase.ButtonAction.GetButton) {
return m_Pressed;
}
// GetButtonDown and GetButtonUp requires the button to be pressed or released within the same frame.
if (Time.frameCount - m_Frame > 0) {
return false;
}
return action == InputBase.ButtonAction.GetButtonDown ? m_Pressed : !m_Pressed;
}
///
/// The object has been destroyed.
///
private void OnDestroy()
{
if (m_VirtualControlsManager != null) {
m_VirtualControlsManager.UnregisterVirtualControl(m_ButtonName);
}
}
}
}