Pseudo code — What is it and why do we use it?
Pseudo code is a method of breaking down a problem into it’s constituent parts, in a human readable format, to allow us to easily form a coded solution to that problem.
Let’s say we want to create a feature that allows us to take user input and apply it to our Player in a 2D game. Our Pseudo code would look something like this —
void Update() {
// receive player input from "WASD" or arrow keys
// convert input into a Vector2
// use Vector2 to move player
}
From this we can determine what variables we may need and take steps to convert our pseudo code into C# code that the compiler can understand. Taking a look, we can see that we’ll want variables for our inputs and also a Vector2 for moving our player.
private Vector2 _direction = new Vector2(0, 0);void Update() {
// receive player input from "WASD" or arrow keys
float xAxis = Input.GetAxis("Horizontal");
float yAxis = Input.GetAxis("Vertical"); // convert input into a Vector2
_direction.Set(xAxis, yAxis); // use Vector2 to move player
transform.Translate(direction * Time.deltaTime);
}
This process allows us to consider each step individually and break down the operations we need to complete into smaller steps. It also allows us the chance to consider other aspects like, ‘should I be running this code here or would this functionality make more sense being in another script’. It is a way of analyzing the code we want to write before we write it.
Once we have our code implemented and tested, we can remove the pseudo code and, if necessary, add a comment that summarizes that block of code.
void Update() {
// Read player input and apply input to player movement float xAxis = Input.GetAxis("Horizontal");
float yAxis = Input.GetAxis("Vertical"); Vector2 direction = new Vector2(xAxis, yAxis); transform.Translate(_direction * Time.deltaTime);
}
Happy Coding!