How to Move a Player Character in Unity - Unity Programming Basics
So I am creating a Shoot em up, a classic genre which I loved back in the 8 bit and 16 bit era of gaming. I boot up Unity and import some game assets, place a background and my player character on screen...but now what? How can I get my character to move?
The answer is through scripting and if you google this topic, there are a multitude of ways in order to do this. Here, I will share my simple method. I've created a script folder in my Project panel and inside have created a C# script simply entitled - "Player.cs". I have then dragged and dropped that script to my player game object. In this case, a rather fancy looking spaceship.
So the first thing I do in the script, is set a Speed variable. This is important as we need a value to tell unity how fast to move the ship in a given direction. I have also made this private variable accessible to the Unity editor by appending the Serialize Field attribute to it. This means that we can change the speed property "on the fly" as the game is running in the editor. Really useful if you want to experiment with values and try to obtain the optimum conditions for the game. For instance in this case, we don't want the spaceship to move to fast or be too slow.
In this case I set the initial value to 5, however if on play testing the game we find that value is a little too fast, we can change it in the editor and experiment with the speed.
Next I create a separate method or function for the movement logic. I try and keep my classes and game design fairly modular and keep the Update function for specific game logic. Within this function, I check the horizontal and vertical axis for specific values. I want to limit the player movement so that they cannot move the whole way up the screen and I want the game to check if they have moved off the left or right horizontal axis and 'wrap around' if this is the case.
So in the above code, you should see that I check the player input for both horizontal and vertical axis and apply a vector for right or up depending on the input. You should also see how the speed variable plays a part in this code. The Time.deltaTime limits the frame rate of the game so if a player is playing on a fast PC the speed of the character is not super fast.
Below is the implementation of the game logic in action!