Touch Joystick

Virtual on-screen joystick for mobile touch input with dynamic or fixed positioning. Outputs normalized Vector2 direction suitable for character movement.

File
TouchJoystick.cs
Unity
2022.3+
Level
intermediate
Size
4.2 KB · 134 lines
Added
2026-03-23
License
MIT
View source

No APIs that Unity 6.0 to 6.6 made obsolete or removed. How this is checked

What it adds to your GameObject

A MonoBehaviour component: attach it to a GameObject. This is the Inspector you get, read from the source: 7 serialized fields with their defaults.

Inspector
Script TouchJoystick
Joystick Settings
Handle Range 50
Is Dynamic
Auto Hide
References
Background None (RectTransform)
Handle None (RectTransform)
Visual
Active Alpha 1
Inactive Alpha 0.3

When to use it

Essential for any mobile game with analog movement — top-down shooters, RPGs, platformers, and action games. Use dynamic mode for casual games where the joystick appears at touch position, or fixed mode for games that need consistent control placement.

Setup

  1. Create a Canvas with Screen Space - Overlay render mode
  2. Add two UI Image children: one for the joystick background and one for the handle
  3. Attach the TouchJoystick script to the background Image
  4. Drag the background and handle RectTransforms into the inspector fields
  5. Read InputDirection from your movement script to move the player
  6. Enable isDynamic for the joystick to appear where the player touches

Features

  • Dynamic or fixed joystick position
  • Configurable handle range
  • Normalized input output (-1 to 1)
  • Visual handle follows touch
  • Auto-hide when not in use

Inspector fields

Every field Touch Joystick exposes in the Inspector, with the default it starts at.

FieldTypeDefaultGroup
Handle RangehandleRangefloat50Joystick Settings
Is DynamicisDynamicbooltrueJoystick Settings
Auto HideautoHidebooltrueJoystick Settings
BackgroundbackgroundRectTransformNoneReferences
HandlehandleRectTransformNoneReferences
Active AlphaactiveAlphafloat1Visual
Inactive AlphainactiveAlphafloat0.3Visual

Public API

What other scripts can call on TouchJoystick.

MemberReturns
OnPointerDown(PointerEventData eventData)void
OnDrag(PointerEventData eventData)void
OnPointerUp(PointerEventData eventData)void
GetInput()Vector2
GetHorizontal()float
GetVertical()float
SetDynamic(bool dynamic)void
SetHandleRange(float range)void
InputDirection propertyVector2
InputMagnitude propertyfloat
IsActive propertybool

Requirements

  • Uses uGUI (UnityEngine.UI): needs a Canvas in the scene.
  • Uses the UI event system: the scene needs an EventSystem object.

Common mistakes

The Canvas must use Screen Space - Overlay or Screen Space - Camera with the correct camera assigned, or touch positions won't map correctly. The background and handle must be separate UI Image children — nesting them incorrectly breaks the drag calculation. If InputDirection reads zero while dragging, check that an EventSystem exists in the scene.

Source code

TouchJoystick.cs, 134 lines, MIT licensed. Paste it into a new C# file of the same name.

TouchJoystick.cs
C#
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class TouchJoystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [Header("Joystick Settings")]
    [SerializeField] private float handleRange = 50f;
    [SerializeField] private bool isDynamic = true;
    [SerializeField] private bool autoHide = true;

    [Header("References")]
    [SerializeField] private RectTransform background;
    [SerializeField] private RectTransform handle;

    [Header("Visual")]
    [SerializeField] private float activeAlpha = 1f;
    [SerializeField] private float inactiveAlpha = 0.3f;

    public Vector2 InputDirection { get; private set; }
    public float InputMagnitude { get; private set; }
    public bool IsActive { get; private set; }

    private RectTransform baseRect;
    private Canvas canvas;
    private Camera uiCamera;
    private Vector2 fixedPosition;
    private CanvasGroup canvasGroup;

    private void Awake()
    {
        baseRect = GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();

        if (canvas.renderMode == RenderMode.ScreenSpaceCamera)
            uiCamera = canvas.worldCamera;

        canvasGroup = GetComponent<CanvasGroup>();
        if (canvasGroup == null)
            canvasGroup = gameObject.AddComponent<CanvasGroup>();

        fixedPosition = background.anchoredPosition;

        if (autoHide)
            canvasGroup.alpha = inactiveAlpha;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        IsActive = true;

        if (autoHide)
            canvasGroup.alpha = activeAlpha;

        if (isDynamic)
        {
            Vector2 localPoint;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                baseRect, eventData.position, uiCamera, out localPoint);
            background.anchoredPosition = localPoint;
        }

        OnDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            background, eventData.position, uiCamera, out localPoint);

        Vector2 clampedInput = localPoint / (background.sizeDelta * 0.5f);

        InputMagnitude = Mathf.Min(clampedInput.magnitude, 1f);

        if (clampedInput.magnitude > 1f)
            clampedInput = clampedInput.normalized;

        InputDirection = clampedInput;

        Vector2 handlePos = clampedInput * handleRange;
        handle.anchoredPosition = handlePos;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        IsActive = false;
        InputDirection = Vector2.zero;
        InputMagnitude = 0f;
        handle.anchoredPosition = Vector2.zero;

        if (isDynamic)
            background.anchoredPosition = fixedPosition;

        if (autoHide)
            canvasGroup.alpha = inactiveAlpha;
    }

    public Vector2 GetInput()
    {
        return InputDirection;
    }

    public float GetHorizontal()
    {
        return InputDirection.x;
    }

    public float GetVertical()
    {
        return InputDirection.y;
    }

    public void SetDynamic(bool dynamic)
    {
        isDynamic = dynamic;
    }

    public void SetHandleRange(float range)
    {
        handleRange = Mathf.Max(10f, range);
    }

    private void OnDisable()
    {
        InputDirection = Vector2.zero;
        InputMagnitude = 0f;
        IsActive = false;
        handle.anchoredPosition = Vector2.zero;

        if (canvasGroup != null)
            canvasGroup.alpha = inactiveAlpha;
    }
}

Next step

Touch ButtonMobile-friendly UI button with press, release, and hold events plus visual feedback. Includes configurable cooldown and hold duration tracking for responsive touch controls.