I’m working on prototyping a top-down 2D game (in 3D) and wanted to start off with a bare bones/boilerplate player controller. I found one on the forum that got me up and running quickly, but it had a little extra code and was not using Input.GetAxis or Input.GetButton. It’s recommended to use these rather than Input.GetKey, because it can also apply to game controllers or other input devices. Then you can set the keys in an options screen. I’m planning on testing with an Xbox controller, so I wanted to start it off properly.
Using Unity’s Character Controller
All you need to do to get your player up and running is:
- Create a big world plane/cube and a cube above it.
- For top-down, point the camera at the cube from above (in this example, this will be a static camera). You’ll probably need to rotate the camera’s X by 90 degrees, and move it a bit.
- Add the following .cs script to your assets folder.
- Add a “Character Controller” component to your cube.
- Add the PlayerController script to your cube (you can drag and drop the script into the inspector tab)
- Click the Play button!
Save the following as PlayerController.cs
Alternate Approach: Use a Rigid Body
Instead, you could add a rigid body to your cube instead of the Character Controller, and try using rigidbody.AddForce(). Rigid bodies work with Unity’s physics engine. Your character will act like a physics object, with momentum and such. So you may lose some precision and have to program things to counteract it. It’s a choice between programming in your physics and fluidity with a Character Controller, or programming towards more precision with a rigidbody.
Note that you can also add a rigidbody with “isKinematic” checked, to an object with a CharacterController, to have it affect the motion of other rigidbodies.
Update 7/26/2015: Removed the Transform.Translate code, and replaced with code using a Character Controller that should be more helpful as a starting point, and for beginners.