2D Character Controller in Unity
Objective: Create a player character that can move horizontally and jump.
We’ll start by adding a Character Controller component to our Bean Cowboy. This handy component acts as both a collider and a rigidbody.
A Character Controller allows us to control the physics of our character. We’ll start by giving him a speed and jump power, and how much gravity to apply to him.
In our Update method, We’ll get the horizontal input (left or right) from the user. We’ll use this to create a Vector3 named direction, applying the _yVelocity (more on this in a moment). This direction will then be multiplied by our speed to get our character’s velocity.
Next we’ll use a very helpful property of our Character Controller; the ability check if the character is grounded. In this case, if it is grounded, and if the player presses a Jump button, the _yVelocity will be set to our character’s _JumpPower. If it is not grounded, the _yVelocity will be decreased by _gravity.
We’ll now replace our character’s y velocity with the new _yVelocity. Finally, we’ll actually Move the character by applying the velocity and multiplying it by Time.deltaTime to make it framerate independent.
Bean Cowboy is now ready for adventure!