Unity Transform: Position
Tags: unity3d, gamedev, beginners, tutorial
Published: 2024-02-25 00:53:05

So I've been learning a lot of Unity lately, but want to really solidify what I've been learning. 

What better way to do that than writing a blog about it? 

In this series we are going to get into some basic, but SUPER important things when getting started with Unity game development.

These things are:
- Position
- Scale
- Rotation

Let's jump right into it!

## Position

So, what you see in this image is the Unity editor, and there is just a white square plane in the middle of the scene.
![Screenshot of a Unity editor showing a white plane](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yc3sq85c7idvge232fh.png)
If you take a close look in the inspector, you can see an area called **transform**. Below that, you can see **position**.  
![Screenshot of a Unity editor showing transform, position, and the scene gizmo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2jinyc9sa5k2lz0ycza.png)
This refers to the position in the scene and is determined by x, y, and z coordinates. In this example, our plane is right in the middle of the scene at `Vector3(0, 0, 0)`. If you get confused by which one is which (meaning the x, y, and z-axis) you can take a look at the thing circled in orange, which comes in handy when changing the position of objects.

> By the way, what even is a `Vector3`?? Well, `Vector3` in Unity represents a 3D position or direction using x, y, and z coordinates. You can learn more about that [here](https://cgcookie.com/lessons/understanding-vector-3).

### Here comes THE CUBE! 

![Screenshot of a Unity scene, there is a purple cube in the center](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o09niecf4zqwfwu35963.png)

So, as you can see we have added a cube on top of our plane. Why?

Well, we are going to make the cube move, it should be able to move forward, backward, left, and right with the arrow keys, and even jump up with the spacebar. By doing this you should be able to have a solid understanding of positioning in Unity.

Some things to be aware of in this post:
- **Horizontal input** (left and right arrow keys) moves the cube left and right along the X-axis (the red one).
- **Vertical input** (up and down arrow keys) moves the cube forward and backward along the Z-axis (the blue one).
- **Jumping** is controlled separately (with the space bar), and changes the cube's position on the Y-axis (the green one).

Now that we've defined some important words that you'll see later on, let's get into the code!

```csharp
public class CubePosition : MonoBehaviour
{
    public float speed = 10.0f;
    public float jumpForce = 10.0f;
    public float horizontalInput;
    public float verticalInput;
    private Rigidbody rb;
}
```
First, we are going to go ahead and define some of our public and private variables. We make some of the variables public so we can easily edit them later in the Unity editor.👇 

![Screenshot of Cube Position script public variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1a7hqwqv9drq9yzyie28.png)

We can directly edit the Speed and Jump Force here, and Horizontal and Vertical Input will change automatically when we click the arrow keys (after we add that logic later).

The private variable `rb` is a reference to the Rigidbody component attached to the cube, which allows us to apply physics-based behaviors to it. Later, we'll use this to make the cube jump!

Next, we have our `Start()` and `Update()` functions.
```csharp
void Start()
{
    rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    Move();
    Jump();
}
```

Here we have two methods, `Start()` runs once when the game starts, right before anything else happens and `Update()` runs once per frame.

`Start()` assigns the cube's Rigidbody component to rb, allowing for physics-based movement.

Then, within `Update()`, we call 2 functions that we will now create!

## Let's Move!

First, the `Move()` method!

```csharp
void Move()
{
    horizontalInput = Input.GetAxis("Horizontal");
    verticalInput = Input.GetAxis("Vertical");

    // this moves the cube forward and backward
    transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
    // this moves the cube left and right 
    transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);      
}
```
The `Move()` method gets player input for movement, using `Input.GetAxis` for both vertical (forward/backward) and horizontal (left/right) directions. Then, we assign these inputs to `horizontalInput` and `verticalInput` variables. 

After that, we use `transform.Translate` to make the game object move.  

```csharp
transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
```

Here, we are controlling the **forward and backward** movement of the object (on the Z-axis). 

`Vector3.forward` (which is the shorthand for `Vector3(0,0,1)`) targets movement along the Z-axis and is multiplied by: 
- `Time.deltaTime` for consistent speed across frames
- `speed` for movement speed
- `verticalInput` for direction based on player input

> If you would like to learn more about Time.deltaTime, you could check out this [resource](https://www.educative.io/answers/what-is-timedeltatime-in-unity). 

Then we do something very similar to allow for **left and right** movement. 

```csharp
transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
```

Here, we use `Vector3.right` (shorthand for `Vector3(1,0,0)`) for movement along the X-axis and multiply it by `Time.deltaTime`, `speed`, and `horizontalInput`. 

![gif of moving cube](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4i7zrcc8b8g7qdad5irq.gif)

Yay! Now our cube can move forward, backward, left, and right!

## Let's Jump!

> Note: it's not generally a good idea to mix two different movement systems, but for the sake of simplicity I am leaving it like this for now😅

Now let's move on to our `Jump()` method: 

```csharp
void Jump()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        // this moves the cube up (jump)
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
}
```
The `Jump()` method makes it possible for our cube to jump into the air. It checks if the player has pressed the space bar 
 with `(Input.GetKeyDown(KeyCode.Space))`. 

If the player has pressed the space bar, there is an upward force applied to the object. We calculate this force by multiplying `Vector3.up` (along the Y-axis) by `jumpForce` (the strength of the jump), and `ForceMode.Impulse` to make sure the force is applied right away.

![gif of cube jumping](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzbvar2n45l6z7h75pc4.gif)

That's all we need to make the cube move with the arrow keys and space bar! Here's the entire script if you would like to try it yourself. But make sure to add a Rigidbody component to the cube so it uses gravity. 

### Complete Script

```csharp
using UnityEngine;

public class CubePosition : MonoBehaviour
{
    public float speed = 10.0f;
    public float jumpForce = 10.0f;
    public float horizontalInput;
    public float verticalInput;
    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        Move();
        Jump();
    }
    void Move()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");

        // this moves the cube forward and backward
        transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
        // this moves the cube left and right 
        transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
        
    }

    void Jump()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            // this moves the cube up (jump)
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
    }
}
```

### The Result
You can test what we've created [here](https://play.unity.com/mg/other/webgl-builds-392859).

Last but not least, here's a video of our cube in action! In this video, you can see how the x, y, and z values change as I click the arrow keys and space bar. 

{% youtube 4kO3hX8ILt4 %}

---

Well, that's all for this post. If you end up making your own cube and adding movement, feel free to share it in the comments! 

If you have any suggestions for how to improve this post or notice anything I have excluded please let me know 😄

If you're looking for more resources to learn how to code check out my [Free Coding Resources](https://elliezub.github.io/Free-Coding-Resources/) site, it has links to a bunch of my favorite courses/resources!

And of course, be sure to check out [Unity Learn](https://learn.unity.com/pathway/junior-programmer), it's an amazing resource!

If you have any questions or want to connect, the best place to reach me is on [Twitter/X](https://twitter.com/elliezub).

Happy coding!