AxisTouchButton.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.EventSystems;
  4. namespace UnityStandardAssets.CrossPlatformInput
  5. {
  6. public class AxisTouchButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
  7. {
  8. // designed to work in a pair with another axis touch button
  9. // (typically with one having -1 and one having 1 axisValues)
  10. public string axisName = "Horizontal"; // The name of the axis
  11. public float axisValue = 1; // The axis that the value has
  12. public float responseSpeed = 3; // The speed at which the axis touch button responds
  13. public float returnToCentreSpeed = 3; // The speed at which the button will return to its centre
  14. AxisTouchButton m_PairedWith; // Which button this one is paired with
  15. CrossPlatformInputManager.VirtualAxis m_Axis; // A reference to the virtual axis as it is in the cross platform input
  16. void OnEnable()
  17. {
  18. if (!CrossPlatformInputManager.AxisExists(axisName))
  19. {
  20. // if the axis doesnt exist create a new one in cross platform input
  21. m_Axis = new CrossPlatformInputManager.VirtualAxis(axisName);
  22. CrossPlatformInputManager.RegisterVirtualAxis(m_Axis);
  23. }
  24. else
  25. {
  26. m_Axis = CrossPlatformInputManager.VirtualAxisReference(axisName);
  27. }
  28. FindPairedButton();
  29. }
  30. void FindPairedButton()
  31. {
  32. // find the other button witch which this button should be paired
  33. // (it should have the same axisName)
  34. var otherAxisButtons = FindObjectsOfType(typeof(AxisTouchButton)) as AxisTouchButton[];
  35. if (otherAxisButtons != null)
  36. {
  37. for (int i = 0; i < otherAxisButtons.Length; i++)
  38. {
  39. if (otherAxisButtons[i].axisName == axisName && otherAxisButtons[i] != this)
  40. {
  41. m_PairedWith = otherAxisButtons[i];
  42. }
  43. }
  44. }
  45. }
  46. void OnDisable()
  47. {
  48. // The object is disabled so remove it from the cross platform input system
  49. m_Axis.Remove();
  50. }
  51. public void OnPointerDown(PointerEventData data)
  52. {
  53. if (m_PairedWith == null)
  54. {
  55. FindPairedButton();
  56. }
  57. // update the axis and record that the button has been pressed this frame
  58. m_Axis.Update(Mathf.MoveTowards(m_Axis.GetValue, axisValue, responseSpeed * Time.deltaTime));
  59. }
  60. public void OnPointerUp(PointerEventData data)
  61. {
  62. m_Axis.Update(Mathf.MoveTowards(m_Axis.GetValue, 0, responseSpeed * Time.deltaTime));
  63. }
  64. }
  65. }