Mobile gaming is pretty hot, and there is always room for developers to deliver more immersive and intuitive user experiences. Touch controls play an essential part within mobile games and, effectively, allow for direct interaction with the game world using one’s screen. Using touch controls in Unity could have a dramatic influence on raising the responsiveness and interactivity of your mobile game. This article is a detailed and high-quality guide on how to create touch controls for Unity mobile games, giving insights you would not find elsewhere.
Why Touch Controls Are Important for Mobile
Touch controls are the most critical commands on a mobile because they provide the most intuitive means of interacting with your game compared to other controllers. Mastery of touch controls helps in the following way:
- Increase involvement of players through intuitive gameplay.
- Make your game more accessible so it can be easily interacted with on any device.
- Provide multi-touch support, the kind of thing used for more sophisticated interactions, such as tapping to zoom or swiping in games.
Before delving into the implementation details, it’s good to know that touch inputs are mostly categorized as these two types in most mobile games:
- Tap – You touch the screen one time (for example, select or shoot).
- Swipe– You move a finger across the screen (for example, move a character or object).
- Pinch– Two-finger gesture that is commonly used for zooming.
- Hold- Pressing a finger on the screen for an extended amount of time.
Touch Controls in Unity using its Input System
Unity supports an easy API to detect and handle touch input. To deal with touches, you also require Unity’s Input class, which supports both multi-touch and gesture-based inputs.
Many popular smartphone games require the keeping track of what fingers are touching the screen, where each finger is located, and what each finger is moving does as a command. Here are Unity’s properties related to touches.
- Input.touchCount: Returns the number of touches occurring on screen.
- Input.GetTouch(i): Returns the Touch structure for the ith touch occurring on screen.
- Touch.phase: Returns the current phase of the touch as Began, Moved, or Ended.
- Touch.position: Returns the position of the touch on screen.
Having known how to use the touch input, it is now time to code.
Step-by-Step Guide to Implementing Basic Touch Controls
1. Setting Up a Unity Project for Mobile Touch Controls
Before writing any code, ensure your Unity project is configured for mobile devices:
- Go to File > Build Settings.
- Select either Android or iOS as the target platform.
- Click Switch Platform.
- Ensure Mobile Input is enabled by going to Edit > Project Settings > Input and adding relevant axes if necessary.
2. Detecting Simple Touch Inputs
Now, we need to detect a single touch. Here we’d like the character or object to move along when the player touches the screen. Here is a simple script to detect single touches:
using UnityEngine; public class SimpleTouchControl : MonoBehaviour { void Update() { // Check if there's at least one touch if (Input.touchCount > 0) { // Get the first touch (index 0) Touch touch = Input.GetTouch(0); // Check if the touch just began if (touch.phase == TouchPhase.Began) { // Get touch position and convert to world position Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10)); // Move the object to touch position transform.position = touchPosition; } } } }
Explanation
- Input.touchCount checks for at least one touch on the screen.
- Input.GetTouch(0) gets the data of the first touch.
- The code moves the object to the screen coordinates where the touch landed by converting the touch position to world coordinates.
3. Multi-Touch Controls
In more advanced games, you might need to allow multiple touches to be processed at once. One touch might be used to move a character, for example, while another could be used to change a camera view.
Here’s one way you can deal with multi-touch input in Unity:
using UnityEngine; public class MultiTouchControl : MonoBehaviour { void Update() { // Loop through all touches for (int i = 0; i < Input.touchCount; i++) { Touch touch = Input.GetTouch(i); if (touch.phase == TouchPhase.Began) { Debug.Log("Touch " + i + " at position: " + touch.position); } } } }
It logs the position of every single touch on the screen. Depending on the logic of your game, you can give each touch a different behavior-for example, use the first touch to control the player and the second for zoom in/out.
Advanced Touch Gestures: Pinch, Swipe, and Drag
1. Implementing Swipe Controls
What’s really useful with swipe controls is in games, for instance, when you need to traverse menus or navigate characters in the display. This is how you might determine and respond to a swipe gesture:
using UnityEngine; public class SwipeControl : MonoBehaviour { private Vector2 startTouchPosition, endTouchPosition; void Update() { if (Input.touchCount == 1) { Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { startTouchPosition = touch.position; } if (touch.phase == TouchPhase.Ended) { endTouchPosition = touch.position; HandleSwipe(); } } } void HandleSwipe() { Vector2 swipeDelta = endTouchPosition - startTouchPosition; if (swipeDelta.magnitude > 100) // Set minimum distance for swipe { if (Mathf.Abs(swipeDelta.x) > Mathf.Abs(swipeDelta.y)) { // Horizontal swipe if (swipeDelta.x > 0) Debug.Log("Right Swipe"); else Debug.Log("Left Swipe"); } else { // Vertical swipe if (swipeDelta.y > 0) Debug.Log("Up Swipe"); else Debug.Log("Down Swipe"); } } } }
Explanation:
startTouchPosition
stores where the touch begins.endTouchPosition
stores where the touch ends.- A swipe is recognized when the difference between the start and end touch positions (
swipeDelta
) exceeds a threshold (100 units in this case).
2. Pinch to Zoom
Pinching is a gesture where two fingers move toward or away from each other, often used for zooming in or out.
Here’s an example of implementing pinch-to-zoom:
using UnityEngine; public class PinchZoomControl : MonoBehaviour { private float previousDistance; private Camera mainCamera; void Start() { mainCamera = Camera.main; } void Update() { if (Input.touchCount == 2) { // Store both touches Touch touch1 = Input.GetTouch(0); Touch touch2 = Input.GetTouch(1); // Calculate the distance between the touches float currentDistance = Vector2.Distance(touch1.position, touch2.position); // Zoom the camera based on the distance between the touches if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved) { if (previousDistance > 0) { float deltaDistance = previousDistance - currentDistance; mainCamera.orthographicSize += deltaDistance * 0.01f; // Adjust zoom speed with this value mainCamera.orthographicSize = Mathf.Clamp(mainCamera.orthographicSize, 2, 10); // Limits zoom range } previousDistance = currentDistance; } } else { previousDistance = 0; } } }
Optimizing Touch Controls Best Practices
Use Responsive UI: All the buttons as well as other widgets you implement in your game should be responsive and should make use of appropriate sizing for a mobile screen.
Use Multi-Touch Judiciously: Multi-touch can really add depth to a game; however, misuse of it simply confuses the players because there are just too many gestures to keep track of. Actually, you should support only the most used gestures like taps and swipes.
Frame Rate Optimisation: When your game maintains an optimal frame rate, the touch interactions will be seamless, free of jerks, and unresponsive controls due to weak frame rates.
Haptic Feedback: Subtle vibrations can be added, which can enhance the tactile experience when players interact with your game.
Conclusion: How to Leverage Touch Controls in Unity
Touch controls are essentially the part of any mobile game and, if implemented properly in Unity, make games very fun for playing. Making use of the solid input system of Unity and defining control directly according to your game requirements will help you create very responsive mobile games. Whether it is simple gesture like touch input or more complex ones like pinch to zoom or swipe, best practices followed for designing touch controls make sure that all those gestures are handled similarly.
Now you know how to implement the magic of touch controls in Unity. Go ahead, add some value to that mobile game, and take it up several notches by providing advanced input systems and, therefore, seamless experiences to your players experience.