FANDOM


This is an example of how an on-screen joystick can be displayed for mobile games, as opposed to the default "drag line".
To use it, place in a script named MobileJoystick and place on a GameObject in your scene.  Supply textures and amend the float values to suit.  Note that this will only work if you use Drag movement, or Direct movement with Touch Screen input.

using UnityEngine;
using System.Collections;
using AC;


public class MobileJoystick : MonoBehaviour
{

    [SerializeField] private Texture2D baseTexture;
    [SerializeField] private Texture2D thumbstickTexture;

    [SerializeField] private float baseTextureSize = 0.1f;
    [SerializeField] private float thumbstickTextureSize = 0.03f;

    [SerializeField] private float maxDistance = 0.1f;

    private Vector2 basePosition;
    private Vector2 thumbstickPosition;


    private void OnEnable ()
    {
        EventManager.OnUpdateDragLine += OnUpdateDragLine;
    }

    private void OnDisable ()
    {
        EventManager.OnUpdateDragLine -= OnUpdateDragLine;
    }

    private void OnGUI ()
    {
        if (KickStarter.playerInput.GetDragState () == DragState.Player)
        {
            if (baseTexture != null)
            {
                Rect baseRect = AdvGame.GUIRect (basePosition.x / Screen.width, basePosition.y / Screen.height, baseTextureSize, baseTextureSize);
                GUI.DrawTexture (baseRect, baseTexture, ScaleMode.ScaleToFit, true, 0f);
            }

            if (thumbstickTexture != null)
            {
                Rect thumbstickRect = AdvGame.GUIRect (thumbstickPosition.x / Screen.width, thumbstickPosition.y / Screen.height, thumbstickTextureSize, thumbstickTextureSize);
                GUI.DrawTexture (thumbstickRect, thumbstickTexture, ScaleMode.ScaleToFit, true, 0f);
            }
        }
    }

    private void OnUpdateDragLine (Vector2 startPosition, Vector2 endPosition)
    {
        basePosition = startPosition;

        float distance = Vector2.Distance (startPosition, endPosition);
        if (distance > (maxDistance * Screen.width))
        {
            thumbstickPosition = startPosition + (endPosition - startPosition).normalized * (maxDistance * Screen.width);
        }
        else
        {
            thumbstickPosition = endPosition;
        }
    }

}