Unity 3D Top-Down Character Controller

Unity 3D Top-Down Character Controller

by NSDG • Jun 1, 2019 • 0 Comments
287
Many people are familiar with game genres such as FPS (First Person Shooter) and RTS (Real-Time Strategy), but there is also a large amount of games that do not fall into just one specific category.
One of such categories is Top-Down Shooter.

Top-Down Shooters borrow some elements form FPS games (playing from a perspective of just one character) and from RTS games (view from atop).
Example of top-down shooters are Hotline Miami, Hotline Miami 2, Original Grand Theft Auto etc.
Hotline Miami 2

In this tutorial I will be showing how to create a simple Top-Down Character Controller in Unity 3D.

Unity version used in this tutorial: Unity 2018.3.0f2 (64-bit)

Part 1: Let's create all the necessary script(s)


For this tutorial we will only need one script:

SC_TopDownController.cs
//You are free to use this script in Free or Commercial projects
//sharpcoderr.com @2019

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]

public class SC_TopDownController : MonoBehaviour
{
    //Player Camera variables
    public Camera playerCamera;
    public Vector3 cameraOffset = new Vector3(7, 20, -1);
    public GameObject targetIndicatorPrefab;
    //Player Controller variables
    public float speed = 5.0f;
    public float gravity = 14.0f;
    public float maxVelocityChange = 10.0f;
    public bool canJump = true;
    public float jumpHeight = 2.0f;
    //Private variables
    bool grounded = false;
    Rigidbody r;
    GameObject targetObject;
    //Mouse cursor Camera offset effect
    Vector2 playerPosOnScreen;
    Vector2 cursorPosition;
    Vector2 offsetVector;
    //Plane that represents imaginary floor that will be used to calculate Aim target position
    Plane surfacePlane = new Plane();

    void Awake()
    {
        r = GetComponent<Rigidbody>();
        r.freezeRotation = true;
        r.useGravity = false;

        //Instantiate aim target prefab
        if (targetIndicatorPrefab)
        {
            targetObject = Instantiate(targetIndicatorPrefab, Vector3.zero, Quaternion.identity) as GameObject;
        }

        //Setup camera position
        playerCamera.transform.position = transform.position + cameraOffset;

        //Hide the cursor
        Cursor.visible = false;
    }

    void FixedUpdate()
    {
        if (grounded)
        {
            // Calculate how fast we should be moving
            Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            targetVelocity = transform.TransformDirection(targetVelocity);
            targetVelocity *= speed;

            // Apply a force that attempts to reach our target velocity
            Vector3 velocity = r.velocity;
            Vector3 velocityChange = (targetVelocity - velocity);
            velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
            velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
            velocityChange.y = 0;
            r.AddForce(velocityChange, ForceMode.VelocityChange);

            // Jump
            if (canJump && Input.GetButton("Jump"))
            {
                r.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
            }
        }

        // We apply gravity manually for more tuning control
        r.AddForce(new Vector3(0, -gravity * r.mass, 0));

        grounded = false;

        //Mouse cursor offset effect
        playerPosOnScreen = playerCamera.WorldToViewportPoint(transform.position);
        cursorPosition = playerCamera.ScreenToViewportPoint(Input.mousePosition);
        offsetVector = cursorPosition - playerPosOnScreen;

        //Camera follow
        playerCamera.transform.position = Vector3.Lerp(playerCamera.transform.position, transform.position + cameraOffset, Time.deltaTime * 7.4f);
        playerCamera.transform.LookAt(transform.position + new Vector3(-offsetVector.y * 2, 0, offsetVector.x * 2));

        //Aim target position and rotation
        targetObject.transform.position = GetAimTargetPos();
        targetObject.transform.LookAt(new Vector3(transform.position.x, targetObject.transform.position.y, transform.position.z));

        //Player rotation
        transform.LookAt(new Vector3(targetObject.transform.position.x, transform.position.y, targetObject.transform.position.z));
    }

    Vector3 GetAimTargetPos()
    {
        //Update surface plane
        surfacePlane.SetNormalAndPosition(Vector3.up, transform.position);

        //Create a ray from the Mouse click position
        Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);

        //Initialise the enter variable
        float enter = 0.0f;

        if (surfacePlane.Raycast(ray, out enter))
        {
            //Get the point that is clicked
            Vector3 hitPoint = ray.GetPoint(enter);

            //Move your cube GameObject to the point where you clicked
            return hitPoint;
        }

        //No raycast hit, hide the aim target by moving it far away
        return new Vector3(-5000, -5000, -5000);
    }

    void OnCollisionStay()
    {
        grounded = true;
    }

    float CalculateJumpVerticalSpeed()
    {
        // From the jump height and gravity we deduce the upwards speed 
        // for the character to reach at the apex.
        return Mathf.Sqrt(2 * jumpHeight * gravity);
    }
}



Part 2: Create the necessary Shader


This tutorial also requires a custom shader, which is needed to make the Aim target overlay the rest of the Objects (always on top).

  • Right click on the Project view -> Create -> Shader -> Standart Surface Shader
  • Name the shader "Cursor"



  • Open the shader, remove everything inside it then paste the code below:

Cursor.shader
Shader "Custom/FX/Cursor" {
	Properties {
		_MainTex ("Base", 2D) = "white" {}
	}
	
	CGINCLUDE

		#include "UnityCG.cginc"

		sampler2D _MainTex;
		
		half4 _MainTex_ST;
						
		struct v2f {
			half4 pos : SV_POSITION;
			half2 uv : TEXCOORD0;
		};

		v2f vert(appdata_full v) {
			v2f o;
			
			o.pos = UnityObjectToClipPos (v.vertex);	
			o.uv.xy = TRANSFORM_TEX(v.texcoord, _MainTex);
					
			return o; 
		}
		
		fixed4 frag( v2f i ) : COLOR {	
			return tex2D (_MainTex, i.uv.xy);
		}
	
	ENDCG
	
	SubShader {
		Tags { "RenderType" = "Transparent" "Queue" = "Transparent+100"}
		Cull Off
		Lighting Off
		ZWrite Off
		ZTest Always
		Fog { Mode Off }
		Blend SrcAlpha OneMinusSrcAlpha
		
	Pass {
	
		CGPROGRAM
		
		#pragma vertex vert
		#pragma fragment frag
		#pragma fragmentoption ARB_precision_hint_fastest 
		
		ENDCG
		 
		}
				
	} 
	FallBack Off
}



Step 3: Setting Up an Example Scene


Let's setup a Top-Down player Controller:

  • Create a new GameObject and call it "Player"
  • Create new Cube and scale it (In my case the scale is (1, 2, 1))
  • Create a second Cube, scale it much smaller and move it to an upper area (This is simply to know which direction the player is looking)
  • Move both Cubes inside the "Player" Object



Now, before going further, let's create an Aim target prefab:

  • Create a new GameObject and call it "AimTarget"
  • Create a new Quad (GameObject -> 3D Object -> Quad) and move it inside the "AimTarget" Object
  • Assign the Texture below to a Quad and change the Material Shader to Custom/FX/Cursor





  • Save the "AimTarget" to Prefab and remove it from Scene



Back to the Player instance:

  • Attach SC_TopDownController script to a "Player" Object (You will notice that it added some additional components such as Rigidbody and Capsule Collider)
  • Scale the CapsuleCollider until it matches the player model (In my case the Height is set to 2 and Center is (0, 1, 0)



  • And finally assign the "Player Camera" and "Target Indicator Prefab" variables in SC_TopDownController



The Player instance is now ready, let's test it:



Everything works as expected!

Interested in obtaining the source project of this tutorial? Click here