Some time ago, I created this game (online playable version) in Unity, and I wanted to be able to play it on my Android phone. Since the input options on the smartphone are slightly different from those on the pc, a certain amount of adjustments were necessary. I won’t go over the specific details on the game mechanics, you can check out these on GitHub, they are described in the README file. However, the basic concept of the game is the movement of a cube to one of the directions up, down, left or right. The information about which direction to use is displayed on the screen.
On a PC, you would use your arrow keys to move the cube. Using Android, you don’t have any keys available. Instead, there is a touchscreen. So you need a way to receive information about user interaction on the touchscreen. Therefore, I’ve created the script GestureRecognizer, which can be seen in the listing below.
The script fetches user input at the first contact, which is saved in the isTouching boolean. The script checks every frame, if the user is touching the screen. If so, it also checks if the user has moved the position on the screen. I use Input.touches for this, since it is an array which contains information about the movement on the screen. All that is left to do now is to check, in which direction the user moved his finger.
However, the immediate evaluation is difficult, as the player will often carry out a minimal movement in a different direction than the intended one (just try it out). For this reason, I have defined a minimum distance that must be exceeded before the script actually communicates the movement. The current movements distance is saved in SwipeDelta, the minimal distance is saved in SWIPE_TOLERANCE, which is assigned 200 units.
To be able to move the cube with this script, it needs to be added to the Update() method of the cubes controller script. To support both touchscreen and keyboards, I simply add an or operator to the if statement:
SwipeControls is simply an instance of the above created GestureRecognizer class.
And that’s basically it! To release a game for android, you have to select the Android entry under File – Build Settings and then click Build. If you have an emulator running or your phone (with USB-debugging enabled) connected to your PC, you can directly run the game on the device. Note, that for building apps for Android, you’ll need to have the Android SDK installed, which can be downloaded directly in Unity.
Subscribe via RSS