Simple Touch Controls in Unity
Implementing basic touchpad controls for mobile games in Unity.
Simple Touch Controls in Unity
I started trying out Unity since Unity 5, which comes with the new UI Component system. The UI Layer makes things very easy. It wraps all UI elements inside a Canvas. It's easy to scale this canvas, and it comes with some predefined scaling and positioning rules.
For creating a custom touch pad, we add a blank image object to the Canvas. We can position this from UI with respect to the camera. We can attach a sprite to this to make it easier for players to identify the input area and its purpose.
The SimpleTouchPad
Class exposes a method GetDirection
which can be checked from the game object controller
to see if there are any movements triggered.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class SimpleTouchPad : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler {
public float smoothing;
private Vector2 origin;
private Vector2 direction;
private Vector2 smoothDirection;
private bool touched;
private int pointerID;
void Awake() {
direction = Vector2.zero;
touched = false;
}
public void OnPointerDown(PointerEventData data) {
// If we already have a pointer, ignore this one
if (touched)
return;
touched = true;
pointerID = data.pointerId;
origin = data.position;
}
public void OnDrag(PointerEventData data) {
// If this isn't the pointer we're tracking, ignore it
if (data.pointerId != pointerID)
return;
// Calculate direction based on the change from origin
Vector2 currentPosition = data.position;
Vector2 directionRaw = (currentPosition - origin);
// Normalize the direction and apply optional smoothing
direction = directionRaw.normalized;
smoothDirection = Vector2.Lerp(smoothDirection, direction, Time.deltaTime * smoothing);
}
public void OnPointerUp(PointerEventData data) {
// If this isn't the pointer we're tracking, ignore it
if (data.pointerId != pointerID)
return;
// Reset our tracking state
touched = false;
direction = Vector2.zero;
smoothDirection = Vector2.zero;
}
public Vector2 GetDirection() {
return smoothDirection;
}
}
How to Use
- Create a Canvas in your Unity scene
- Add an Image UI element to serve as your touchpad
- Attach this script to the Image
- Set the smoothing value in the inspector (higher values = more responsive)
- In your player controller script, reference this touchpad and use the GetDirection() method to control movement
This touchpad controller is ideal for mobile games where you need a joystick-style control without a physical joystick. The smoothing option makes it particularly good for character movement in third-person or top-down games.