First, you’re going to write some code to make the player character move when the
PlayerController script has been added.
To write the code, follow these instructions:
1. Find the Update function. This function is called, which means that the
instructions in it are completed (executed), regularly while the game is running.
2. Add the following instruction within the Update function braces:
Vector2 position = transform.position;
This instruction stores the current position of the GameObject.
Here’s an explanation of your change:
This instruction declares (creates) a new variable called position. Variables are
named places that you can store data so that you can retrieve the data when you
need to. You can think of a variable like a locker or cupboard with a name on it.
The variable’s type is Vector2. Different variable types can store different data.
The Vector2 type can store two numerical values, so it’s ideal for 2D coordinates.
The equal sign (=) tells the computer what to store in the variable.
transform.position tells the computer to get the to store the Position property X
and Y values that are contained within the Transform component. You can use the dot
(called the dot operator) to access data contained within something else.
The semicolon (;) tells the computer that the instruction is finished.
3. Add a second instruction to the Update function:
position.x = position.x + 0.1f;
Based on the previous instruction that you wrote, what do you think this
instruction does? Take a moment to try and work it out before reading on.
Here’s an explanation of your change:
This instruction sets a new horizontal (x-axis) position for the GameObject.
You have accessed the x-coordinate value stored within the position variable that
you declared in the previous instruction.
The equals sign (=) tells the computer to store a new value for the x-coordinate.
The new position for the coordinate is the current position (position.x) plus 0.1.
f indicates a number with a decimal place (called a floating point number).
The semicolon (;) tells the computer that the instruction is finished.
4. Add a final instruction to the Update function:
transform.position = position;
What do you think that this instruction does? Take a moment to consider before
reading on!
Here’s an explanation of your change:
This instruction sets the Position property in the Transform component using your
position variable.
Previously, the updates that you made were being stored in your variable but hadn’t
been applied to the GameObject. This instruction will actually make the player
character move.
Remember, the semicolon to end the instruction is very important — if you don’t
include it, an error message will display in the Unity Editor console window and
the code won’t work.
5. Save your script changes, then return to Unity Editor.