Skip to content

Instantly share code, notes, and snippets.

@thsbrown
Created April 29, 2020 16:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thsbrown/2ea08bb054d701c45c1c645c0a067b29 to your computer and use it in GitHub Desktop.
Save thsbrown/2ea08bb054d701c45c1c645c0a067b29 to your computer and use it in GitHub Desktop.
ETCDpadButtonInvoker
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// Allows invoking of <see cref="ETCDPad"/> buttons script side.
/// </summary>
public class ETCDpadButtonInvoker : MonoBehaviour {
/// <summary>
/// The image component that is used to display the dpad
/// </summary>
[Tooltip("The image component that is used to display the dpad")]
public Image dpadImage;
/// <summary>
/// The event system we are using to send events to our ETCDpad. If null will grab current event system.
/// </summary>
[Tooltip("The event system we are using to send events to our ETCDpad. If null will grab current event system.")]
public EventSystem eventSystem;
private Sprite dpadSprite;
private void Awake() {
dpadSprite = dpadImage.sprite;
eventSystem = EventSystem.current;
}
/// <summary>
/// Presses the left button of the dpad down
/// </summary>
[Button]
public void InvokeButtonLeftDown() {
var left = dpadImage.transform.position;
left.x -= dpadSprite.bounds.size.x * dpadSprite.pixelsPerUnit / 2;
var pointerEventData = new PointerEventData(eventSystem) {
position = left
};
ExecuteEvents.Execute(dpadImage.gameObject, pointerEventData, ExecuteEvents.pointerDownHandler);
}
/// <summary>
/// Presses the right button of the dpad down
/// </summary>
[Button]
public void InvokeButtonRightDown() {
var right = dpadImage.transform.position;
right.x += dpadSprite.bounds.size.x * dpadSprite.pixelsPerUnit / 2;
var pointerEventData = new PointerEventData(eventSystem) {
position = right
};
ExecuteEvents.Execute(dpadImage.gameObject, pointerEventData, ExecuteEvents.pointerDownHandler);
}
/// <summary>
/// Releases any buttons that are being pressed on the depad
/// </summary>
[Button]
public void InvokeButtonUp() {
ExecuteEvents.Execute(dpadImage.gameObject, new PointerEventData(eventSystem), ExecuteEvents.pointerUpHandler);
}
}
@thsbrown
Copy link
Author

Read more about all the different handlers you can invoke on gui elements here ExecuteEvents Event Handlers.

This bit of code was created because I was trying to setup a test for our players movement including the input inertia of the gui controls. Specifically we are using the dpad from this quite frankly outdated asset to handle our mobile input.

Hope this helps someone!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment