Basic Rigidbody Controller – Top Down

Below is a very basic rigidbody controller for a 2D or 3D top Down game. This code has support for both keyboard and gamepad input. Put this script on your player with a rigidbody attached.

Make sure that the rigidbody constraints are as follows:
Position:
x – false
y – true
z – false

Rotation:
x – true
y – true
z – true

using UnityEngine;
using System.Collections;

public class playercontrols : MonoBehaviour {

  public float speed = 6.0f;
  private Vector3 moveDirection;
  private float normalized = 1.0f;

  // Update is called once per frame
  void Update () {
    transform.position = new Vector3(transform.position.x, -transform.position.z / 10000.0f + 0.005f, transform.position.z);
    float leftRight = Input.GetAxisRaw("Horizontal");
    float upDown = Input.GetAxisRaw("Vertical");
    Vector3 velocity = new Vector3(leftRight, 0, upDown);

    if(Input.GetKey("a") || Input.GetKey("d") || Input.GetKey("left") || Input.GetKey("right") || velocity.x < 0 || velocity.x > 0 ) {
        if(Input.GetKey("a") || Input.GetKey("left") || velocity.x < 0 ) {
            moveDirection.x = -speed;
        }
        if(Input.GetKey("d") || Input.GetKey("right") || velocity.x > 0 ) {
            moveDirection.x = speed;
        }
    } else {
        moveDirection.x = 0;
    }

    if(Input.GetKey("w") || Input.GetKey("s") || Input.GetKey("up") || Input.GetKey("down") || velocity.z < 0 || velocity.z > 0 ) {
        if(Input.GetKey("w") || Input.GetKey("up") || velocity.z > 0 ) {
            moveDirection.z = speed;
        }
        if(Input.GetKey("s") || Input.GetKey("down") || velocity.z < 0 ) {
            moveDirection.z = -speed;
        }
    } else {
        moveDirection.z = 0;
    }

    if(rigidbody.velocity.x != 0 && rigidbody.velocity.z != 0) {
        // to make the player move diagonally without making him go faster we reduce the total speed with this fancy number
        normalized = 1/1.4142145f;
    } else {
        normalized = 1.0f;
    }

    // add the force
    rigidbody.velocity = moveDirection * normalized;
  }
}