Mobile Endless Runner Game Development Series With Unity3D — Part 1, Player Controls [Beginner]

Swipe Detection Explanation

Ali ALACAN
5 min readMar 22, 2018

Why Unity3D?

If you are interested in developing games then you have probably heard about Unity3D has become one of the most popular game engines in the mobile game development community. First of all, it’s free for personal use and you are not restricted from the main features of it. Also, it has cross-platform support that made the development process easier and less time consuming for multiple platform deployments. Of course there are some features that need to be adapted for individual platforms but still, you can dig up Unity’s asset store to find a packed solution like IAP and notifications works for both platforms.

What Will We Achieve?

In this series, I will try to explain how can we use Unity3D to develop a cross-platform endless runner game with low poly art which I found from the Unity asset store. With this part, we will find out how to detect finger swipes using touch phases and touch positions in Unity3D. Next, we’re gonna write their callbacks and trigger some functions in them. Beginner level knowledge of Unity3D is enough to understand what is going on in this project. But still, you can take a glance at this series to find out how Unity handles this kind of processes even if you are not touched Unity before. I will add the complete script to end of the post but we’re gonna continue with code blocks for a better explanation.

Here some information on tools and stuff that I will use to develop my project:

  • Unity3D 2017.3.1f1,
  • C# for coding,
  • [Optional]Some 3D assets for visualization,(Primitive objects are enough for this but it’s funnier this way)
  • Visual Studio 2017 Community Edition (or Mono Develop if you are Mac OS user),
  • Unity Profiler for performance testing, (Will be used for detecting infinite road spawn system’s performance impact later,
  • Mobile Device for Testing. This is important because you can’t simulate gestures on Play mode without additional development.

Let’s start with Touch. According to Unity Documentation, Touch API isStructure describing the status of a finger touching the screen.” But it’s not enough to detect whether the player is swiped or not. To understand finger gestures, Unity is providing us TouchPhase that defined as “An enum type that contains the states of possible finger touches.” This information is enough at this stage of the post but of course, you can read more about TouchPhase at Unity Documentation. So we have Touch and TouchPhase to develop a simple swipe detection script.

Let’s fill our Update function now:

//Variable definitionsprivate Vector2 fingerDownPos; // for holding finger down position
private Vector2 fingerUpPos; // for holding finger up position
public bool detectSwipeAfterRelease = false; //*1
//Update is called once per framevoid Update ()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUpPos = touch.position;
fingerDownPos = touch.position;
}
//Detects Swipe while finger is still movingif (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease) //*1
{
fingerDownPos = touch.position;
//TODO Check swipe here
}
}
//Detects swipe after finger is releasedif (touch.phase == TouchPhase.Ended)
{
fingerDownPos = touch.position;
//TODO Check swipe here
}
}
}

[1]: detectSwipeAfterRelease: Set this bool is true if you want to see an action performed after the player released finger from the screen. But this is a bad idea for our use case because it feels laggy and slow. We want the player to react as fast as possible and change lanes with cat reflexes using this simple trick.

Now it’s time to check swipes at our TODO lines. First of all, we need to detect if swipe vertical of horizontal. For achieve this let’s create two simple functions named as VerticalMoveValue () and HorizontalMoveValue().

float VerticalMoveValue ()
{
return Mathf.Abs (fingerDownPos.y — fingerUpPos.y);
}
float HorizontalMoveValue ()
{
return Mathf.Abs (fingerDownPos.x — fingerUpPos.x);
}

We could use those values directly but it is more flexible if you divide your code functions by their main purposes. With doing this, you will have more control over your code.

It is important to detect swipe and trigger callbacks at the right phase of finger movement. Try different thresholds for best user experience.

Now we are ready to create swipe checker function that uses these values and calls related callback functions with directions. But first, let me explain what swipe threshold is and why we need it. For instance, imagine that you’ve placed a pause button to the up right corner. Since we are getting finger positions on the screen, (not from canvas or other components) swipes on button’s surface are still affects our functions. What if we do not have a threshold and user clicks button during the gameplay? Yes. It might trigger some of our callbacks and that is an unwanted situation for us.

In the example below, I defined float SWIPE_THRESHOLD and set it to 20f.

For vertical swipes:


if (VerticalMoveValue () > SWIPE_THRESHOLD && VerticalMoveValue () > HorizontalMoveValue ())
{
Debug.Log(“Vertical”);

if (fingerDownPos.y — fingerUpPos.y > 0)
{
OnSwipeUp ();
} else if (fingerDownPos.y — fingerUpPos.y < 0)
{
OnSwipeDown ();
}
fingerUpPos = fingerDownPos;
}

For horizontal swipes:


else if (HorizontalMoveValue () > SWIPE_THRESHOLD && HorizontalMoveValue () > VerticalMoveValue ())
{

Debug.Log(“Horizontal”);
if (fingerDownPos.x — fingerUpPos.x > 0)
{
OnSwipeRight ();
} else if (fingerDownPos.x — fingerUpPos.x < 0)
{
OnSwipeLeft ();
}
fingerUpPos = fingerDownPos;
}

else
{
Debug.Log(“No Swipe Detected!”);
}

Next thing to do is put together our code pieces and see the big picture. This is our main swipe checker function’s skeleton.

Finally, our SwipeDetector script is shaped like this:

Let’s summarize what we talked about in this post:

  • Decide what your function is serving for and extract other codes with different purposes,
  • Always use thresholds for avoiding unwanted swipe detections,
  • Decide swipe detection phase that suits best to your gameplay mechanics.
Relax, they are just zombies and I hate them.

Here you can see a simple demonstration of our near-complete SwipeDetector script. Of course, we can always add some animations and stuff to improve overall quality but simply, it works like a charm!

For testing it your self, place a UI Text component on screen and change its text in callbacks.

That was all for this part. We’re gonna take a look at how can we move the player with code and create performance-friendly infinite road creation system at part 2. Until then, stay well.

--

--