DEV Community

Cover image for Unity Transform: Position
Ellie
Ellie

Posted on • Updated on

Unity Transform: Position

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
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
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.

Here comes THE CUBE!

Screenshot of a Unity scene, there is a purple cube in the center

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!



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


Enter fullscreen mode Exit fullscreen mode

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

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.



void Start()
{
    rb = GetComponent<Rigidbody>();
}

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


Enter fullscreen mode Exit fullscreen mode

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!



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);      
}


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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.

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



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


Enter fullscreen mode Exit fullscreen mode

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

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:



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


Enter fullscreen mode Exit fullscreen mode

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

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



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);
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

The Result

You can test what we've created here.

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.


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 site, it has links to a bunch of my favorite courses/resources!

And of course, be sure to check out Unity Learn, it's an amazing resource!

If you have any questions or want to connect, the best place to reach me is on Twitter/X.

Happy coding!

Top comments (2)

Collapse
 
kodikos profile image
Jodi Winters

I'm worried that you are mixing two different movement systems, that could lead to weird behaviour. If you notice, you are using the transform to change the X and Z position, but using the rigidbody to do the jump on the Y-axis. Transform is literally setting the position of the cube in 3D space. But rigidbody is a part of the physics engine and you are applying a force and asking it to calculate it's position. It's usually best to stick to one or the other. Doing it all with position is not particularly arduous, most flappy bird implementations will do it.

Collapse
 
elliezub profile image
Ellie

Hi Jodi!! Thanks for the feedback, I didn't know that mixing the two was typically not a good idea, I'll try and update the article to stick to one or the other ๐Ÿ˜„