Day 5: Simple Movement in Unity

Gerald Clark
2 min readApr 5, 2021

--

We accomplished moving our player game object to the center of the game view with a simple line of code yesterday. Today we will work on getting user input and having that control the movement.

When you manipulate the position of an object its called Translation. There are several ways to accomplish the same thing. Lets check out a few of them.

In this first example we have local float variables. One of them is getting the Horizontal axis and the other is getting the vertical axis. It is getting access to the Input Manager with Input.GetAxis(). This takes a string. That is why we have “Horizontal” and “Vertical” in quotation marks. To actually move the object, we need the second half of this code. transform.Translate(). This is what actually moves the object. The Vector3.right and Vector3.up is exactly like saying Vector3(1,0,0) and Vector3(0,1,0). Se we have our Vector3. We multiply it by our horizontalInput and verticalInput, the _speed variable, and the Time.deltaTime. We declared our _speed variable at the top of our code. It is a float value we set to 3.5f. Time.deltaTime: the completion time in seconds since the last frame changes. This will help slow down our game object so its more manageable.

There is an easier way to accomplish this however.

Here I have commented out the previous lines of code. We now have everything in one line. We just needed another local variable called direction. This is a new Vector3 that we have assigned the horizontalInput as the X axis, the verticalInput as the Y axis, and a 0 for the Z since we are working in a 2D space. Now all we need to write is transform.Translate(direction * _speed * Time.deltaTime); to move our player!

Hop into Unity and see your work in action!

--

--

Gerald Clark
Gerald Clark

Written by Gerald Clark

Father Game Developer Music Composer Sound Designer

No responses yet