Creating a Physics-Based Character Controller in Unity
2.5D Game Development
There are lots of ways you can control your character but there is always one thing in common in them that is rigidbody, colliders and such. But why take the long road when unity has given us the platform to move straight.
We can add character controller component in our character and it will handle all the collision of our character. It provides us with various properties such as Slope limit, Step offset, Radius, Height, etc which can be used to further configure our controller to match our needs.
We added a character controller but how to go about moving it?
Lets first start by creating a platform where our player can move and jump.
Add a capsule gameobject in your scene and it will be your player for now. add platforms for player to move and jump into. Now to configure the player, remove the capsule collider component from your player and add character controller component in its place.
Now that your player is set-up in your scene view, lets write some code to make our player move. Create a Player script and lets get at it.
Now lets define some variables inside the script to get going. First define a character controller variable to get access to the properties inside the character controller component inside player. Then define the speed variable at which player will be moving and the gravity variable to make player fall when in air. Finally, add a variable to store the jump value of player and another float variable to store y velocity which we will be talking about later.
Now get the reference to the character controller inside the player inside the start method.
Now store a input float that detects the ‘A’, ‘D’ or ‘Left-Arrow key’, ‘Right-Arrow key’ press and create a new vector move so that player can move in that direction.
Then define velocity which simple means moving at a certain direction with certain speed.
Now check if the player is colliding with the ground using isGrounded feature of character controller. If the player is on ground and if the player hits space key then define the y velocity script the jump height.
If the player is on air then define gravity which will drag the player down towards the ground.
Now, set the velocity in y-axis to _yVelocity variable which has the jump and gravity values applied.
Then move your player using Move method having velocity with respect to time.
And this is how it will look like in the Game view.