Scripting the Player (part 1)
Now that we have set up the platforms and collectables we need to scrip the player component so that it can traverse the level we have created.
In Unity, there is a component which is a preset for attaching basic player functions to any game object. This component is called “Character Controller” and it comes with the all the necessity that a player character requires, this includes jump and jump height, collision triggers and also player movement. The Character controller also functions without using the Rigidbody component which means that we can freely set the limitation of gravity and other forces manually.
Create an new C# script and name it “Player” and drag the script into the player object. Then double click the script to open it up in Visual Studios. To begin we first need to have access to the Player Controller therefore we create an new handle for it.
Then we need to create movement via Unity Input presets. In the void Update method, we are going to define the horizontal Input as a float and have Unity’s preset input handle the controls, this includes left and right arrow keys and also “A” and “D” keys as movement. Then we need to have the define the Direction which is basically the horizontal input.
As a bonus we are also gong to define “Velocity” so the player can move faster than one pixel per second. Since velocity is basically direction multiplied by speed, we need to give an private handle for “speed” and assign it a float value. For me, I assigned my speed as 5.
Finally to finish off the movement function, we need to make the character controller move according to the Direction + input. In the Unity scripting API, there is an set code for making the character controller move which is basically “ _controller(the name you gave your character controller) dot Move”. The move is then calculated by the Velocity. Now you should have an playable character that is able to move left and right, and also collide with the platforms.