Let’s get moving.
* An empty scene
* A 3D Cube named “Player” (give it a snazzy color)
* A new script named “Player” attached to the Player game object
* Typing fingers
This game will have simple 2D motion, so I have to align my view so positive y is up and positive x is right.
The first thing I want to do is to take control of the Player’s position. Let’s define a starting point for our cube. In my Player script I’ll add the following line to the Start method: transform.position = new Vector3(0, 0, 0);
Now, every time I run the program, the Start method will grab the player by their transform’s position property and yank them in the middle of the map.
Next I need to tell the player how to interpret player input. To do this, first I need to define speed. I will make it a serialized field so I can tweak it on the fly if I need to.
In order to know what the player wants to do I need the script to listen for their input. So, I can declare a local variable for horizontal input, and make it equivalent to the horizontal control axis from the build settings.
Finally, I can multiply the horizontal input (between -1 and 1) with both the speed variable and time, and then use those values to translate the player left or right.
Here’s what that looks like:
I want two axes of motion, so I can duplicate the whole above process, swapping out horizontal for vertical. Once that’s done, here’s the player script:
Now, let’s test it out.
Fantastic. But, it seems a bit wasteful to repeat ourselves so much. Vector3 has three vectors after all. Let’s combine both the x and y values into one Vector3 and call that my direction variable.
Now we can ditch two of the four lines of code.
I can move. But the camera is fixed, and I could easily wander out of view and become lost. I need boundaries.
What I’ll do is restrain my y movement to between the middle of the screen and the bottom. Also, I want an old-school wraparound effect for the x-axis. To all of that, I need to set some conditions. If the player’s y position is at or higher than the upper limit, keep them at the upper limit. Likewise for the lower limit. If the player’s x position is beyond the right or left limit, move them to the opposite limit.
Codewise, it looks like this:
And when we switch back over to unity, we see that we do indeed have some boundaries.
The last thing I want to do is clean this all up. I’ll replace the if statement for the y axis by giving the player a new Vector3 with the y-axis bounded by a Mathf clamp, like so:
I can’t do the same for the x-axis because of the wraparound effect, but now things are much tidier.
Next time we’ll dive into variables a little more deeply, and discover how they become the building blocks of your programming.