Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- public enum JoystickType {
- Round,
- Square
- }
- public struct Bounds {
- public Vector2 min;
- public Vector2 max;
- }
- public class Joystick : MonoBehaviour, IDragHandler, IEndDragHandler {
- public Vector2 output {
- get {
- return p_output;
- }
- }
- public JoystickType joystickType = JoystickType.Round;
- public Vector2 deadZone = Vector2.zero;
- public float maxDistance = 50f;
- public bool smooth = true;
- new private RectTransform transform;
- private Bounds bounds;
- private Vector2 defaultPosition;
- private Vector2 position;
- private Vector2 p_output;
- private void Start() {
- transform = GetComponent<RectTransform>();
- defaultPosition = transform.position;
- bounds.max = (Vector2)transform.position + Vector2.one * maxDistance;
- bounds.min = (Vector2)transform.position - Vector2.one * maxDistance;
- }
- public void OnDrag(PointerEventData data) {
- position = transform.position;
- position += data.delta;
- switch(joystickType) {
- case JoystickType.Round:
- position = Vector2.ClampMagnitude(position - defaultPosition, maxDistance) + defaultPosition;
- break;
- case JoystickType.Square:
- position.x = Mathf.Clamp(position.x, bounds.min.x, bounds.max.x);
- position.y = Mathf.Clamp(position.y, bounds.min.y, bounds.max.y);
- break;
- }
- p_output = position - defaultPosition;
- p_output /= maxDistance;
- if(Mathf.Abs(p_output.x) < deadZone.x)
- p_output.x = 0f;
- if(Mathf.Abs(p_output.y) < deadZone.y)
- p_output.y = 0f;
- if(smooth) {
- p_output.x *= Mathf.Abs(p_output.x);
- p_output.y *= Mathf.Abs(p_output.y);
- }
- transform.position = position;
- }
- public void OnEndDrag(PointerEventData data) {
- transform.position = defaultPosition;
- p_output = Vector2.zero;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement