Move it, GameObject!
In this article, we’ll quickly look at some ways to move our objects in our scenes.
- Create or open a Unity project.
- Create two cubes, one with a RigidBody with Gravity off and scale the other one to be a horizontal or vertical wall.
That is all we need. Ready, set, go!
In your project, you’ll use the Old Input System to get our inputs. You don’t have to do anything as it is already enabled by default. For now, it’s fine. But it’d be great to use the New Input System, a much better and improved system. Don’t worry, I have an article planned for it.
- Create a new C# script
- Add it to our cube.
- Declare a new Vector2 variable, where it will store our input. Call it “moveInput”.
- Assign the Input value to that variable by getting the Input Axis. You can check your inputs in
Project Settings > Input Manager.
- Put your line of code inside the Update method. We want to constantly receive our inputs.
With that code, we’ll be able to start moving our objects… but there’s something that isn’t right about that. The GameObject moves faster diagonally.
This happens because we didn’t normalize our input value, making our movement direction higher.
How do we fix this? Like this!
Fun fact! Did you know that the Halo: Master Chief Collection PC port has this diagonal issue? They probably overlooked it because, when playing with a controller, the inputs are already normalized!
The completion time in seconds since the last frame — Unity API
Time.deltaTime will make our movement frame independent. We don’t want our object to move slower or faster depending on the user’s framerate.
With that out of the way, we are ready to add the code to move our GameObject.
You can instantly move the GameObject to a new position by assigning it a new Vector3. In our case, we’ll move our cube to our Input vector.
The cube remains static in those few positions. That’s because we are setting the cube position to that input. To properly move, we’ll add the input to that position. Oh, and we’ll also need a speed variable, as we’ll move slowly without it.
Moves the transform in the direction and distance of
translation. — Unity API
While that approach works, it’s best to only use it to instantly move a GameObject to a position. A better approach at moving a GameObject would be to use this method, as it provides more control over how to move that object (move it relative to a local or world axis, and relative to another Transform).
Now you can move your GameObject whoever you like! But, as you can see, it jitters a lot when you move towards a wall. This is due to the RigidBody pushing back against the wall, and transform.position or transform.Translate() not caring about collisions.
But more on that in a future article!