Simple 2D Controls
I have spent the last several project focusing on the 3D realm, and it seemed a good time to transition back to 2D and create a modular chassis that can be used to create a plethora of 2D platformer style games.
In that vein, I began a new project and quickly laid out a few platforms for testing.
Next I added a capsule for the player and a few prefabbed “coins” for the player to collect. I also threw in a few materials to give visual clarity.
NOTE: Everything must be at 0 on the Z axis in order for this 2D game to operate in the 3D project space.
Moving on to the player character, I created a new C# script (PlayerController) and added a Character Controller to the capsule.
In the PlayerController script, we need a handful of variables to ensure that the player can move correctly.
A speed variable(_speed)
A gravity variable (_gravity)
A jump height variable (_jumpHeight)
We also need to reference the Character Controller component in Start.
With that all set, I created a new void (Movement) to hold the logic needed for the player movement.
Inside this function, I reference Unity’s hardcoded horizontal axis.
I also set two new local variables, direction and velocity.
In order to move horizontally, we simply need to tell the Player Controller component to move based on the velocity variable.
Jumping is a bit more nuanced, but still very simple!
To start, we need to check if the player is grounded. Fortunately, the character controller tracks this for us and can be referenced.
I also needed to be able to cache the jump height to avoid stuttering issues as the script reruns each frame. To do so, I created another float variable (_yVelocity).
If we are not grounded, then we apply gravity to the cached velocity value, dropping the player back to the ground.
Finally, we set velocity.y to be equal to _yVelocity.
Finally, I wanted to add a double jump feature to give the player some more skill expression as the game become more complicated. To do so, I needed a new boolean to track if the player can do a double jump (_canDoubleJump).
A few edits to the jump logic to incorporate the double jump.
When we jump, the bool flips to true, allowing a second jump. Once we use the second jump, it flips to false, and will not turn back again until we are grounded.
Now the core movement of the platformer is complete. In my next article, I will be incorporating the collectable coin system so the player has a win objective!