Sunday, April 6, 2014

Unity Endless Runner Tutorial #2 - Android Version

Original Tutorial
http://catlikecoding.com/unity/tutorials/runner/

My version of the game (Version Log)
http://www.hansadrian.com/Stuff/Endless%20Runner%20Tutorial/build.html

GitHub Gist (for full code files)
https://gist.github.com/HansNewbie/10005219/38e71e0c7358d15335412cbbbcdbb3facee36094

Completed Project Files (V0.6.1)
Buy this on Selz Selz powering ecommerce websites

For version 0.2, I added Android version - I updated the code with support for Android touch control. Check the Gist for the complete codes.

In order for the Android version to be able to quit with the back button, we need a game exit manager that would handle the input of "esc" button. Embed the code found at GameExitManager.cs into an Empty named Game Exit Manager under Managers, just like the other managers.

To support the touch input, I refactored the code for jumping. I abstract the whole codes as such:

private void Jump() {
    if (touchingPlatform) {
        rigidbody.AddForce(jumpVelocity, ForceMode.VelocityChange);
        touchingPlatform = false; // This allow one jump after colliding with side of platform, but not more
    }
    else if (boosts > 0) {
        rigidbody.AddForce(boostVelocity, ForceMode.VelocityChange);
        boosts -= 1;
        GUIManager.SetBoosts (boosts);
    }
}


Now, for all input of "jump", replace it with the line below:

if ((Input.GetButtonDown("Jump")) ||
    ((Application.platform == RuntimePlatform.Android) && (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))) {
    // your code here
}

So what happens here is if the platform is Android, we will detect if there is any touch occurring through touchCount > 0. If there is, we will take it as a tap by reading when the player touch the screen - thus TouchPhase.Began - since we would like it to be responsive.

For the case of Runner.cs, the code within would be Jump();. This is not enough; the tutorial use the "jump" input as trigger for game start as well. Thus, you need to replace if (Input.GetButtonDown("Jump")) with the snippet above as well in GUIManager.cs.

To make the instruction suitable for Android, we need to change the instruction into "Tap to play". To do this, add the following snippet in GUIManager.cs under Start.
if (Application.platform == RuntimePlatform.Android) {
 instructionsText.text = "Tap to play";
}

As you see, currently we need to do this for all input in the future. I tried to think of a way to abstract all input, whether from input manager or our own logic for touch input. I can't find an elegant solution to this. Will share my solution if I find one.

No comments:

Post a Comment