Simple Player Movement

Seeing as we’re building a viable prototype, we’re not going to start off with a rad looking spaceship. Rather, we’ll be using primitives to represent our primary objects.

There’ll be our player cube, the enemy sphere, capsule lasers…I think that’s it for now.

So there’s our player cube, hanging out below the enemy sphere.

First we’re going to make it move, then we’ll get into actually controlling it.

So how do we make game objects do stuff? Scripts.

Right+click on your Assets folder and select Create then C# Script.

Name the script as the name is highlighted, then hit enter.

Next, drag the script and drop it onto the player object in the hierarchy.

And now you have the script on the player!

Let’s fire up VS Code and get this turkey moving.

First thing, let’s assign an initial position to the player when the game starts — in this case we’ll use the coordinates (0, 0, 0).

This is also known as a Vector3. It’s essentially any given point within the 3D space of Unity’s game environment.

Here’s the code we need:

We’re calling the transform component of the object, and then specifically the position component of the transform -> transform.position

And then we need to assign it a new Vector3, a new position in the 3D space.

Transform component in Unity inspector

So when the game starts, it calls the transform’s position and says, “HEY! Get over to (0, 0, 0)!” and starting at frame 1, the player object will be there.

And now we can get into more fun movement, though still super basic.

From here, we’ll move to the Update function as this is what happens after Start.

We start again with the transform, but instead of referencing its position, we’re now telling it to move, or to translate through 3D space, hence transform.translate.

This code is now telling our player object to move to a new Vector3 of (1, 0, 0), relative to itself, once per frame.

And there is nothing in the code telling it to stop; so what do you think will happen when we save the change and hit play in Unity?

In the GIF below, we have the scene view on top and the game view on bottom.

Once we push the play button, in frame 0, the player cube will move to (0, 0, 0) and from frame 1 to eternity, it will move to the right — the positive direction on the x-axis-1 virtual meter.

Now I have to go get that cube…so we’ll see you back here tomorrow to look at actually harnessing the cube and moving it deliberately.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cliff Bailey

Cliff Bailey

Software Developer w/ADHD learning and doing life.