Reader small image

You're reading from  Unity 2022 Mobile Game Development - Third Edition

Product typeBook
Published inJun 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613726
Edition3rd Edition
Languages
Tools
Right arrow
Author (1)
John P. Doran
John P. Doran
author image
John P. Doran

John P. Doran is a passionate and seasoned Technical Game Designer, Software Engineer, and Author who is based in Incheon, South Korea. His passion for game development began at an early age. He later graduated from DigiPen Institute of Technology with a Bachelor of Science in Game Design. For over a decade, John has gained extensive hands-on expertise in game development working in various roles ranging from game designer to lead UI programmer working in teams consisting of just himself to over 70 people in student, mod, and professional game projects including working at LucasArts on Star Wars: 1313. Additionally, John has worked in game development education teaching in Singapore, South Korea, and the United States. To date, he has authored over 10 books pertaining to game development. John is currently a Technical Game Design Instructor at George Mason University Korea. Prior to his present ventures, he was an award-winning videographer.
Read more about John P. Doran

Right arrow

Mobile Input/Touch Controls

How players interact with your project is probably one of the most important things in it to get right. While player input is added for all projects, no matter what platform you are using, this is one area that can make or break your mobile game.

If the controls that are implemented don’t fit the game that you’re making, or if the controls feel clunky, players will not play your game for long stretches of time. While many people consider Rockstar’s Grand Theft Auto series of games to work well on consoles and PC, playing the games on a mobile device provides a larger barrier of entry, due to all of the buttons on the screen and the replacement of joysticks with virtual versions that don’t provide haptic feedback in the same manner as other platforms.

Mobile and tablet games that tend to do well typically have controls that are simple, finding as many ways to streamline the gameplay as possible. Many popular games require...

Technical requirements

This book utilizes Unity 2022.1.0b16 and Unity Hub 3.3.1, but the steps should work with minimal changes in future versions of the editor. If you would like to download the exact version used in this book (and there is a new version out), you can visit Unity’s download archive at https://unity3d.com/get-unity/download/archive.

You can also find the system requirements for Unity at https://docs.unity3d.com/2022.1/Documentation/Manual/system-requirements.html under the Unity Editor system requirements section.

You can find the code files present in this chapter on GitHub at https://github.com/PacktPublishing/Unity-2022-Mobile-Game-Development-3rd-Edition/tree/main/Chapter03.

Using mouse input

Before we dive into mobile-only solutions, I do want to point out that it is possible to write input that works on both mobile and PC by using mouse controls. Mobile devices support using mouse clicks as taps on the screen, with the position of the tap/click being the location where the finger has been pressed. This form of input provides just the position where the touch happened and indicates that a press has happened; it doesn’t give you all of the features that the mobile-only options do. We will discuss all of the features you have using mobile-specific input later on in this chapter, but I think it’s important to note how to have click events on the desktop as well. I personally use the desktop often for ease of testing on both a PC and my device, so I don’t have to deploy to a mobile device to test every single change made in a project.

To use desktop-based mouse click events for the movement of a player, first, inside Unity, open up...

Moving using touch controls

Unity’s Input engine has a property called Input.touches, which is an array of the Touch objects. The Touch struct contains information on the touch that occurred, with information such as the amount of pressure on the touch and how many times you tapped the screen. It also contains the position property, such as Input.mousePosition, that will tell you what position the tap occurred at, in pixels.

Note

For more information on the Touch struct, check out https://docs.unity3d.com/ScriptReference/Touch.html.

Let’s look at the steps to use touch instead of mouse inputs:

  1. Adjust our preceding code to look something like the following:
    /// <summary>
    /// FixedUpdate is a prime place to put physics
    /// calculations happening over a period of time.
    /// </summary>
    void FixedUpdate()
    {
        // Check if we're moving to the side
        var horizontalSpeed = Input.GetAxis("Horizontal...

Using Unity Remote

Another way to check how our game works using mobile devices is through an application that Unity has created called the Unity Remote. Created with Unity 5, it has been a while since the application has been updated, but it still works with the current version of Unity; however, it does require us to do some additional work and setup.

Android setup For Unity Remote

In order to set up a phone to use Unity Remote, we will need to download the app and learn how to enable debugging mode, so in this section, we’re going to see just how to do that:

  1. To start, open up the Google Play app, and from there in the search bar, type in unity remote:
Figure 3.5 – Searching for the Unity Remote application

Figure 3.5 – Searching for the Unity Remote application

  1. Select the Unity Remote 5 app. Afterward, you’ll be brought to the screen in order to install it, so click on the Install button and wait for it to finish downloading.
Figure 3.6 – The Unity Remote 5 app page on Google Play

Figure...

Implementing a gesture

Another type of input that you’ll find in mobile games is that of a swipe, such as in Kiloo’s Subway Surfers. This allows us to use the general movement of the touch to dictate a direction for us to move in. This is usually used to have our players jump from one position to another or move quickly in a certain direction. So, we’ll go ahead and implement that using the following steps, instead of our previous movement system:

  1. In the PlayerBehaviour script, go ahead and add some new variables for us to work with:
    [Header("Swipe Properties")]
    [Tooltip("How far will the player move upon swiping")]
    public float swipeMove = 2f;
    [Tooltip("How far must the player swipe before we will
        execute the action (in inches)")]
    public float minSwipeDistance = 0.25f;
    /// <summary>
    /// Used to hold the value that converts
    /// minSwipeDistance to pixels
    /// </summary>
    private float minSwipeDistancePixels...

Scaling the player using pinches

The concept of using touch events to modify things in the game can also be applied to other methods of touch interaction, such as using finger pinches to zoom in and out. To see how to do this, let’s adjust the PlayerBehaviour script so that we can change the player’s scale, using two fingers to pinch or stretch out the view:

  1. Open up the PlayerBehaviour script and add the following properties:
    [Header("Scaling Properties")]
    [Tooltip("The minimum size (in Unity units) that the
        player should be")]
    public float minScale = 0.5f;
    [Tooltip("The maximum size (in Unity units) that the
        player should be")]
    public float maxScale = 3.0f;
    /// <summary>
    /// The current scale of the player
    /// </summary>
    private float currentScale = 1;
  2. Next, add the following function:
    /// <summary>
    /// Will change the player's scale via pinching and
    /// stretching...

Using the accelerometer

Another type of input that mobile has, but PC doesn’t, is the accelerometer. This allows you to move in the game by tilting the physical position of the phone. The most popular example of this is likely the movement of the player in games such as Lima Sky’s Doodle Jump and Gameloft’s Asphalt series. To do something similar, we can retrieve the acceleration of our device with the Input.acceleration property and use it to move the player. Let’s look at the steps to do just that:

  1. We may want to allow our designers to set whether they want to use the Accelerometer mode or ScreenTouch, which we used previously. With that in mind, let’s create a new enum with the possible values to place in the PlayerBehaviour script above the Swipe Properties header:
    [Tooltip("How fast the ball moves forwards
        automatically")]
    [Range(0, 10)]
    public float rollSpeed = 5;
    public enum MobileHorizMovement
    {
     ...

Detecting touch on game objects

To add something else for our player to do, as well as to demonstrate some additional input functionality, we’ll ensure that if the player taps an obstacle, it will be destroyed. We will use the following steps to modify our existing code to add this new functionality, utilizing the concept of raycasts:

  1. In the PlayerBehaviour script, add the following new function:
    /// <summary>
    /// Will determine if we are touching a game object
    /// and if so call events for it
    /// </summary>
    /// <param name="screenPos">The position of the touch
    /// in screen space</param>
    private static void TouchObjects(Vector2 screenPos)
    {
        /* Convert the position into a ray */
        Ray touchRay =
            Camera.main.ScreenPointToRay(screenPos);
        RaycastHit hit;
        /* Create a LayerMask that will collide with...

Summary

In this chapter, we have learned the main ways in which games are controlled when working on mobile devices. We also learned how we can use mouse inputs, touch events, gestures, and the accelerometer to allow players to interact with our game.

In the next chapter, we will explore the other main way that players interact with a game by diving into the world of user interfaces and creating menus that can be enjoyed, no matter what device a user is playing the game on.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity 2022 Mobile Game Development - Third Edition
Published in: Jun 2023Publisher: PacktISBN-13: 9781804613726
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
John P. Doran

John P. Doran is a passionate and seasoned Technical Game Designer, Software Engineer, and Author who is based in Incheon, South Korea. His passion for game development began at an early age. He later graduated from DigiPen Institute of Technology with a Bachelor of Science in Game Design. For over a decade, John has gained extensive hands-on expertise in game development working in various roles ranging from game designer to lead UI programmer working in teams consisting of just himself to over 70 people in student, mod, and professional game projects including working at LucasArts on Star Wars: 1313. Additionally, John has worked in game development education teaching in Singapore, South Korea, and the United States. To date, he has authored over 10 books pertaining to game development. John is currently a Technical Game Design Instructor at George Mason University Korea. Prior to his present ventures, he was an award-winning videographer.
Read more about John P. Doran