Loading lessons...
Mobile & Touch Input
Mobile & Touch Input
Developing games for mobile devices requires handling touch screens, multi-touch gestures, and virtual joystick interfaces.
Detecting Touches in C#
To check for finger touches on mobile screens:
void Update()
{
// Check if any fingers are touching the screen
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Touch started at: " + touch.position);
}
else if (touch.phase == TouchPhase.Moved)
{
Debug.Log("Finger is sliding: " + touch.deltaPosition);
}
}
}
Touch Phases
The TouchPhase enum describes the state of a finger:
Began: The finger touched the screen this frame.Moved: The finger moved on the screen.Stationary: The finger is touching the screen but not moving.Ended: The finger was lifted from the screen.Canceled: The system canceled tracking for the touch (e.g. phone call interrupt).
Virtual Joysticks & Buttons
For mobile action games, you can place UI images on screen that act as virtual controls. The Input System package includes a Onscreen Stick and Onscreen Button component:
- Place a UI Image for a joystick knob.
- Add the On-Screen Stick component.
- Assign a control path (e.g.
Gamepad/leftStick). - The stick knob converts drag gestures into standard gamepad inputs automatically.
TL;DR
- Use
Input.touchCountandInput.GetTouchto read mobile screen inputs. - TouchPhase enums track finger actions (Began, Moved, Ended).
- Use On-Screen Stick components to implement mobile virtual joysticks easily.