Making a touchscreen joystick in Unity

In this tutorial, we will learn how to create the joystick UI for touchscreen and use it to move an object in Unity. I will be using Unity 2021.1.13 for this tutorial.

Before starting with the tutorial, it’s recommended to read our post on the basics of UI design.

Making drawings

  • Go to Paint.
  • Make a small circle and fill it with the color or your choice.
  • Save the image as inner_circle.
  • Draw another circle that is bigger than the previous one and do not fill the inside part. Save the image as outer_circle
  • Open both the images in gimp or photoshop and make the background of your sprites transparent.
  • The images should look as in the preview.
  • Import both the drawings into Unity.
picture of inner controller
Inner Circle
outer circle of joystick
Outer Circle

Setting up the UI

  1. Select the images in the project window and set the texture type to Sprite.
  2. Go to scene view and click add>UI>image and name it as Joystick_border.
  3. Add another UI image as the child of Joystick_border and name it as Joystick Controller.
  4. Adjust the height and width of joystick controller to look like in the image below.
Joystick UI

Adding code to joystick

Note: This code will not work with the new input system. If you have installed the new unity system then you will have to remove it using the package manager.

We are using the Drag handler event to read the movement of the joystick.

Free Unity asset banner

Create a new script callled Dragscript and add it to the joystick controller.

Copy and paste the code below to the Dragscript

using UnityEngine;
using UnityEngine.EventSystems;


public class Dragscript : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler {

	public GameObject player;
	Vector3 move;
	Vector3 initialpos;
	Vector3 distance;
	void Start()
	{
		move = Vector3.zero;
	}
	void Update()
	{
		player.transform.position+=move*Time.deltaTime;
	}

	#region IBeginDragHandler implementation
	public void OnBeginDrag (PointerEventData eventData)
	{
		initialpos = transform.position;
		move = Vector3.zero;

	}
	#endregion

	#region IDragHandler implementation

	public void OnDrag (PointerEventData eventData)
	{	
		distance = Input.mousePosition-initialpos;
		distance=Vector3.ClampMagnitude(distance,45*Screen.width/708);
		transform.position =initialpos+ distance;
		move = distance.normalized;


	}

	#endregion

	#region IEndDragHandler implementation

	public void OnEndDrag (PointerEventData eventData)
	{
		move = Vector3.zero;
		transform.position = initialpos;
	}


	#endregion

}

Drag and drop the player you want to move to the Dragscript.

Play the game and the player should move based on the joystick movement.

Joystick movement demo
Top online courses in Development

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.