Top 5 Ways To Move Gameobject In Unity (With Examples)

Share on social media

In this article, I will cover the Top 5 ways to move gameobject in unity. There are multiple ways of moving objects but the ways I am going to show you in this article are the most useful ones. So read the article till the end.

Moving an object in unity is not a complex thing but sometimes it’s necessary to know the right way or the most suitable way for the requirement. 

I will cover different ways of moving objects in this article and I will also explain in which condition they are helpful so it will help you to understand which one you should use.

Let’s begin with the basic way of moving objects before jumping into the Top 5 Ways. Let’s first understand the basic aspects of moving the gameobject in unity. Especially it will be helpful for you to understand if you are a beginner in unity.

Top 5 ways to move gameobject in unity
Top 5 ways to move gameobject in unity

How To Move Gameobject In Unity

First, Let’s quickly look at the most simple and common way to move gameobject in unity except the Top 5 ways. 

The most common way is to modify the Position of the gameobject using its Transform Component and set a new Vector3 In the Update Method.

For Example:


public float speed = 5f;
    
// Update is called once per frame
void Update()
{
    transform.position += new Vector3(speed * Time.deltaTime,0, 0);
}

The above code is moving the gameobject in the right direction with a particular speed and we are unity Time.deltatime to keep the movement constant each frame.

It would look like this:

Time.deltaTime In Unity

Time.deltaTime is the interval in seconds from the last frame to the current one. Its value varies for each frame.

In our case, we are moving objects in the update method, which also executes each frame so to make the movement constant, we use Time.deltaTime as a multiplier.

Let’s see the difference with and without deltaTime and how it affects the movement. For both movements, I will use the speed value 5. Let’s check it.

There is a huge difference, The without deltaTime object is moving much faster because the deltaTime object is using the deltaTime as a multiplier which reduces the vector value that we are adding to each frame. apart from this deltaTime gives you smooth and constant movement.

If you only want to move the gameobject in a single particular axis then instead of using the new Vector3 you can directly use the shorthand vector properties.

For Example:

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    transform.position += Vector3.right * speed * Time.deltaTime;
}

But these shorthand vector properties work on world space. It won’t be affected by the gameobject’s rotation.

If you want to move it in local space means relative to the gameobject’s local position and rotation then you can use the transform properties which return you the normalized vector on a particular axis on which you want to move the object.

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    transform.position += transform.right * speed * Time.deltaTime;
}

Vector3 Shorthand Properties In Unity

Vector3 direction properties work on world space, changing object’s rotation won’t affect it’s direction. Vector3 shorthand properties for each direction.

Vector3.forward   // (0,  0,  1)
Vector3.back      // (0,  0,  -1)
Vector3.up        // (0,  1,  0)
Vector3.down      // (0,  -1, 0)
Vector3.right     // (1,  0,  0)
Vector3.left      // (-1, 0,  0)

Transform’s Direction Vectors In Unity

Transform direction properties work in local space and they are based on the object’s local transform like position and rotation. it returns the normalized vector. Let’s understand it by an example.

For Example: Let assumes we have a gameobject and we are moving it in the right direction. But now if we rotate the Z-axis by 45 degrees and now if we move the object it will move diagonally in to right and upward direction simultaneously.

Here are the transform’s direction vector properties.

transform.forward  // object's forward direction
-transform.forward // object's back direction
transform.up       // object's up direction
-transform.up      // object's down direction
transform.right    // object's right direction
-transform.right   // object's left direction

I hope now you have understood the basic part of moving the gameobejct. So this was the common way to move gameobject in unity. 

 Now let’s move on to the top 5 ways of moving gameobject in unity.

Top 5 Ways To Move Gameobject In Unity

Now we will see the Top 5 ways to move gameobject in unity. each way we will discuss here is going to do the same job in the end which is to move the object, then why so many options? because each way has its use case and each one is very useful. 

Let’s explore all the top 5 ways to move gameobject in unity one by one. Let’s get started.

1. How To Move Object Using Transform.Translate

The first way we will discuss is the Transform.Translate. So far we learnt to add the vector each frame to move the gameobject. Translate function will also do the same job but it’s different and also more convenient and flexible. 

Translate gives us the flexibility whether we want to move the gameobject in world space or local space (relative to gameobject’s local transform).

Let’s see how to use Transform.Translate function in unity.

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.right * speed * Time.deltaTime, 
    Space.Self);
}

In the second parameter we have pass the Space.Self to specify that we want to move gameobject in the local space not in the world space. 

However it’s by default is Space.Self only so if we event don’s pass the second parameter it will still move the gameobject in the local space only.

So we can also write it like this:

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.right * speed * Time.deltaTime);
}

Both of the above code is the same and will move the gameobject in the local space only. I showed both so that you don’t get confused between the two.

But one thing to note here is that we have used the Vector.right and as we learned above that Vector3 shorthand properties work on world space then how it is supposed to work on local space? that is because of the Translate function and that’s the beauty of it. 

Let’s test this code by rotating the gameobject in the Z axis by 45 degrees and as you can see above we are using Vector3.right which represents the red axis in the editor, which is the X axis. which means the gameobject should move in the right and upward direction simultaneously.

Now let’s see what it would look like.

As you can see the gameobject is moving in the local space. The movement is working based on the gameobject’s local Axis.

Now let’s see how to move the gameobject in the world axis.

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    transform.Translate(Vector3.right * speed * Time.deltaTime,
    Space.World);
}

So to move the gameobject in the world space you just need to use “Space.World” in the second parameter.

Now to test it we will use the same rotation that we used above. So the gameobject is still rotated into the Z axis by 45 degrees.

Let’s see how it will work this time.

So as you can see even though the gameobject’s transform has some rotation in its Z axis it’s still moving in the right direction only. Because now it is calculated based on the World Axis only and the gameobject’s transform position and rotation will not affect it.

When should I use the Transform.Translate?

Transform.Translate is very useful when you want to move an object which has some rotation but you want to ignore it or the opposite where you want to move an object relative to its transform’s local position and rotation. Transform.Translate can do both jobs for you without any extra effort.

So that’s about it, Hope you understand how to use it and when it is useful. Let’s move on to the second method of Top 5 ways to move gameobject in unity.

2. How To Move Object Using Vector3.MoveTowards

The second way from the Top 5 ways to move gameobject in unity is Vector3.MoveTowards.

Vector3.MoveTowards allows you to move a gameobject toward the target object at a set speed without overshooting the target object. Unlike Lerp this is based on Speed, not Time.

Let’s see how to use Vector3.MoveTowards In Unity.

public float speed = 5;
public Transform target; 
    
// Update is called once per frame    
void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, 
    target.position, speed * Time.deltaTime);
}

Vector3.MoveTowards Takes the 3 parameters, First represents the current position, the second represents the target position, And the third represents the Speed

It modifies a Vector3 value to move towards a target at a set speed without overshooting it. It moves at a constant speed which has given in the third parameter.

Now let’s see the result of the above code.

As you can see above it moves toward the target position at a given speed. since it moves at a constant speed which has given so it may not be as smooth as Lerp in comparison, which we will be taking a look at in the below methods.

When should I use Vector3.MoveTowards?

Vector3.MoveTowards is very useful when you want to move a gameobject toward the target position at a constant speed. 

But if you want to move the gameobject towards the target position based on time instead of speed then you should take a look at Lerp, this will give you more smooth movement.

Now let’s move on to the third method of Top 5 ways to move gameobject in unity.

3. How To Move Object Using Keyboard Inputs

Sometimes we want to move the gameobject on the inputs, so in this method, we will see how you can move the gameobject on inputs on any device.

The logic is simple, You just need to add the direction in the transform’s position and multiply it with the input value.

In this article, we will understand it by the keyboard’s arrow inputs.

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 movement = new Vector3(x, 0, z);
    transform.Translate(movement * speed * Time.deltaTime);
}

The above code would enable you to move the gameobject with the arrow keys of the keyboard, it’s a player movement that normally we use in the games to move to the character on input.

Which looks like this:

In above video, the normal movement is working fine when I am moving the object in the single direction but when I pressed two arrow buttons together (down + right arrow) then you can notice that the speed was increased. 

The reason is the magnitude of the vector, when I moved it in the single direction then the magnitude of the “movement” variable was 1. but when using diagonal direction the magnitude was 1.4 and for that reason the movement was 1.4x faster.

You can check the magnitude by debugging the “movement”.

Debug.Log(movement.magnitude);

There are two ways to fix this issue, First is by clamping the magnitude to 1 and the second is by normalizing the vector.

By Clamping The Magnitude 

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 movement = Vector3.ClampMagnitude(new Vector3(x, 0, z), 1);
    transform.Translate(movement * speed * Time.deltaTime);
}

By Normalizing The Vector

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 movement =  new Vector3(x, 0, z).normalized;
    transform.Translate(movement * speed * Time.deltaTime);
}

Both of the above solutions will fix the issue. Now let’s understand when you should use it.

When should I use Keyboard Inputs To Move Objects?

This method is handy to create a player movement or any movement you want to map on the keyboard or device input.

Now let’s move on to the fourth method of the Top 5 ways to move gameobject in unity.

4. How To Move Object Using Lerp (Linear Interpolation)

This method is similar to Vector3.MoveTowards and different at the same time. Let’s first understand what is Lerp.

Lerp or Linear Interpolation, The Lerp allows us to interpolate linearly between two values. It can be specified using a minimum and maximum value (a & b) and an interpolation value (t), the interpolation value (t) returns a point on the scale between a and b.

Formula Of Lerp In Unity

a + (b – a) * t

Unlike the Vector3.MoveTowards The Lerp moves toward its target based on the time not speed. So in this method you can control the time that the movement should take. 

Let’s see how to use the lerp in unity.

public Transform target;
    
// Update is called once per frame
void Update()
{
    transform.position = Vector3.Lerp(transform.position ,
            target.position, Time.deltaTime);
}

So this is normal way of using the Lerp to move the object toward its target.

Which will look like this:

As you can see in the above video, The object is moving toward the target object. But as you can see the object is moving faster in the beginning and slowing down in the end.

Also it’s not controlled by time, and it’s not the right way to use it.

Let the first understand the basics of Lerp.

Lerp takes 3 arguments a,b, and t.

Let’s understand the third parameter (t) as a percentage (%), t is clamped from 0 to 1, so 0 means 0% and 1 means 100%.

So if you pass the value of t as 0 so it will return you the value of which means the object won’t move at all and if you pass the value of t as 1 then it will return you the value of b which means the object will directly teleport to the position of the target.

To simplify it let’s understand it by the given formula, Now let’s take one simple example:

a = 2;
b = 6
t = 0.5;

return value = (b – a) * t, which will be 2.

In the above you code if you see so we were passing the transform.position in the parameter so each frame the distance between two points was decreasing and that is the reason the movement was faster in the beginning and slows down as it gets near to the target object.

In order to make to make the Lerp movement controlled by time, the parameters a and must be remain constant means it should not change over the period of frames and the third parameter should be dynamic.

Let’s see how we can do it, For example, I want to move the object from its own position to the target’s position in the 10 seconds. 

public Transform target;
private float desiredDuration = 10f;
private float elapsedTime;

private Vector3 startPos;

private void Start()
{
    startPos = transform.position;
}

// Update is called once per frame
void Update()
{
    elapsedTime += Time.deltaTime;
    float durationCompleted = elapsedTime / desiredDuration;
    transform.position = Vector3.Lerp( startPos, 
        target.position, durationCompleted);
}

Let see the result of the above code.

That’s it, The above movement is based on the time and complete movement is taking exactly 10 seconds. In comparison to Vector3.MoveTowards the Lerp movement is smoother.

If you want to understand the Lerp movement in more depth then I would suggest you read this article What Is Lerp In Unity? The Right Way To Use It Where not only you will understand the Lerp calculation in depth but you will also learn some other ways to use it. Hope it will help you to understand the Lerp.

When should I use Lerp or Linear Interpolation?
Some developers specifically beginners get confused between Vector3.MoveTowards and Lerp. And don’t understand exactly when they should which one.
 
so the answer is simple, If there is movement in your game that need to be controlled by time, let’s say you are developing a simulation game where the movement time should be fixed and should not depend on the speed then in this kind of case you should use the Lerp. 
 
Now let’s move on to the final method of the Top 5 ways to move gameobject in unity.

5. How To Move Object Using Physics

The final method in the Top 5 ways to move gameobject in unity is using physics. All the above methods we have seen were based on the Transform but in this method, we will be using the Rigidbody to apply physics on the gameobject and with the help of that we will move the gameobject.

There are three ways in physics to move gameobject in unity.

  • Moving gameobject using Adding Force.
  • Moving gameobject using Velocity.
  • Moving gameobject using MovePosition.
Let’s explore them all one by one.

a. Moving Gameobject Using Adding Force

The first way to move a gameobject using physics is by adding force. So how to add force to the gameobject?

In unity, When you create a new 3d gameobject by default you will get the Collider Component but adding force that’s not going to be helpful, So to get the gameobject in the physical presence you will need to add the Rigidbody component.

Collider is like a physical body but that has no use until it has a rididbody attached to it.

The first step is to add the Rigidbody Component on the gameobject. Now let’s see the code on how to add force to the gameobject in unity.

public float force = 500f;
private Rigidbody rigidbody;

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

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rigidbody.AddForce(Vector3.right * force, ForceMode.Force);
    }
}

The first thing to notice here is that I have used the FixedUpate In my code because all the physics calculations should be calculated in the FixedUpdate. The reason is that Update fluctuate according to the FPS of the application.

However, in FixedUpdate the timeStamp is fixed, which is 0.02, which means FixedUpdate will call 50 times each second.  you can also change it from Edit > Settings > Time > Fixed Timestep. It is not advisable to change it until you have actual requirements to change its value. 

Back to the AddForce, As you can see in the above code we are adding force to the gameobject in the right direction when we press the Space Key. 

Let’s see what it will look like:

It moves an object in the right direction with a force of 500 and we are using the ForceMode.Force.

To add more impulsive force to the object, you can use ForceMode.Impulse. Let’s try this one out and see how it works.

public float force = 40f;
private Rigidbody rigidbody;
    
private void Start()
{
    rigidbody = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rigidbody.AddForce(Vector3.right * force, ForceMode.Impulse);
    }
}

Notice that we are using the force unit 40 only though we used the 500 in ForceMode above. 

Let’s see the result:

As you see the difference between the force of both modes, ForceMode.Force and ForceMode.Impulse. Even with a force of 40, it is much more impulsive than the force of 500 in the Force Mode.

There are different-different ForceMode.

ForceMode Properties In Unity

  • Force: Add a continuous force to the rigidbody, using its mass.
  • Acceleration: Add a continuous acceleration to the rigidbody, ignoring its mass.
  • Impulse: Add an instant force impulse to the rigidbody, using its mass.
  • VelocityChange: Add an instant velocity change to the rigidbody, ignoring its mass.
When should I use Rigidbody AddForce?

You can use the AddForce function of rigidbody to create a player jump or some kind of explosion effect or some kind of throwing effect. It can be used anywhere, where you want forced movement instead of continuous movement.

b. Moving Gameobject Using Velocity

Above we see the forced movement, now let’s see the continuous movement using the velocity. First, lets us understand what is the velocity in the rigidbody.

The velocity vector of the rigidbody. It represents the rate of change of Rigidbody position. The velocity is a world-space property.

This is the same as Translate as we learned about it above. But this time we are using the Rigidbody instead of the Transform component.

Let’s see how to move the gameobject using rigidbody’s velocity.

public float speed = 150f;
private Rigidbody rigidbody;

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

void FixedUpdate()
{
    rigidbody.velocity = Vector3.right * speed * Time.fixedDeltaTime;
}

In the above code, We are assigning the new vector in the velocity vector of the rigidbody to move it in a particular direction, in our case we are moving it in the right direction and multiplying it with speed and Time.fixedDeltaTime

same as we used Time.deltaTime in the Update function since the FixedUpdate function does not call each frame so it has a fixed time stamp which is Time.fixedDeltaTime. 

Let’s see the result of the code:

The cube is rotating while moving, We can fix it by freezing the rotation in the rigidbody. Let’s Fix it.

Freeze The Rotation Of Rigidbody
Freeze The Rotation Of Rigidbody

This will fix the rotation issue while moving. Now the movement will look like this:

That’s how to you can move the gameobject using the Rigidbody Velocity.

When should I use Rigidbody Velocity?

You can use the Rigidbody Velocity to move an object where you are dealing with physics at the same time. For Instance, you can also use the drag on the rigidbody that slows down the velocity that looks more realistic movement but it depends on the requirements. So in this type of case, you should consider using it.

c. Moving Gameobject using MovePosition

This is the final way of physics and the Top 5 ways to move gameobject in unity. The MovePosition is the function of the rigidbody which moves the kinematic Rigidbody towards the position.

There are many times when we want the rigidbody to be kinematic and simultaneously want to move it. In this kind of case, this is the best function that will come in handy for you.

Kinematic Rigidbody In Unity

The kinematic rididbody does not affect by collisions, joints, or any forces from other rigidbodies. If any non-kinematic rididbody will collide with it then the collision force will apply to the non-kinematic rididbody but not to the kinematic rididbody.

It is very useful when you want to move the object using script or animation and don’t want it to break through physics. The rigidbody will be under full control of animation or script control by changing the transform.position

Enable the isKinematic bool in the rigidbody to make the rigidbody kinematic.

To Make The Rigidbody Kinematic

Let’s see how to use MovePosition.

public float speed = 5f;
private Rigidbody rigidbody;

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

void FixedUpdate()
{
    Vector3 newPosition = transform.position + transform.right * speed * Time.fixedDeltaTime;
    rigidbody.MovePosition(newPosition);
}

This is how you can move the kinematic rigidbodies. I hope you will find this method helpful for you, maybe in the future

When should I use Rigidbody MovePosition Function?

You can use the Rigidbody’s MovePosition function to move the gameobject which has a kinematic rigidbody attached to it.

Final Thoughts

If you have read the complete article then you know that we discussed the Top 5 ways to move gameobject in unity. I hope you would have found something helpful or learned a new way to move a gameobject today. 

Each way has its use case, If you are still confused about which one should you use just analyze your requirements and I have already briefed the use case of each method, read it again and you can figure out the way.

But if you still have any doubts you can simply leave a comment below I will help you.

In the end, I also want to suggest you one plugin that I use in my projects to move the objects, it is DOTween. It makes your work easier. 

FAQs

How To Move An Object In Unity 2d

You can move the 2d object in unity, using many ways like Transform.Translate or by updating the position in the update method. 

For Example, Let’s try Transform.Translate:

 

public float speed = 100f;

void Update()
{
    transform.Translate(transform.right * speed* Time.deltaTime);
}

You can use it to move both 2D and 3D gameobjects. For more details, you can read it in detail above 

Unity Move 2d Object With Arrow Keys

As we have already seen in the above article how to move an object with arrow keys and the same can be used for the 2D keys.

Here is the code to move a 2d object with arrow keys in unity.

public float speed = 5;
    
// Update is called once per frame
void Update()
{
    float xAxis = Input.GetAxis("Horizontal");
    float yAxis = Input.GetAxis("Vertical");
    Vector3 movement = new Vector3(xAxis, yAxis, 0).normalized;
    transform.Translate(movement * speed * Time.deltaTime);
}

That’s how you can move the 2D gameobject with arrow keys in unity. The only difference between the code we used above in the article and this is before we used the vertical input in the Z axis and here we are using it in the Y axis, because of the change in dimensions.

Unity Move Object With Mouse
To move an object with mouse there are different ways in unity. Let’s say you want to move the UI image with mouse. In this case you can you use the Unity’s OnDrag Method.

This is how you can do it.

using UnityEngine;
using UnityEngine.EventSystems;

public class LerpObject : MonoBehaviour, IDragHandler
{ 
    private Vector2 mousePosition = new Vector2();
    private Vector2 startPosition = new Vector2();
    private Vector2 differencePoint = new Vector2();

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButton(0))
        {
            UpdateMousePosition();
        }
        if(Input.GetMouseButtonDown(0))
        {
            UpdateStartPosition();
            UpdateDifferencePoint();
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        /*Minus the difference point so you can pick the 
        element from the edges, without any jerk*/

        transform.position = mousePosition - differencePoint;
    }

    private void UpdateMousePosition()
    {
        mousePosition.x = Input.mousePosition.x;
        mousePosition.y = Input.mousePosition.y;
    }

    private void UpdateStartPosition()
    {
        startPosition.x = transform.position.x;
        startPosition.y = transform.position.y;
    }

    private void UpdateDifferencePoint()
    {
        differencePoint = mousePosition - startPosition;
    }
}

The above script will work fine with the UI elements like Images, But if you want to move the Sprite renderer or 3D gameobject then you should check this article for more detail

 

How Do You Instantly Move An Object In Unity?
To instantly moving an object in unity you can use Rigidbody’s AddForce function which can instantly move an object by force.
 
For Example:
public float force = 60f;
private Rigidbody rigidbody;
    
private void Start()
{
    rigidbody = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rigidbody.AddForce(Vector3.right * force, ForceMode.Impulse);
    }
}

It will instantly move an object depending on the force. You can read more about it here.

What Is The Best Way To Move An Object In Unity?

There is no one best way to move an object in unity, It totally depends on the requirements of how you want to move the gameobject.

These are the Top 5 ways to move gameobject in unity that we have discussed in this article.

    1. How to move objects using Transform.Translate
    2. How to move objects using Vector3.MoveTowards
    3. How to move objects using keyboard Inputs
    4. How to move an object using Lerp (Linear Interpolation)
    5. How to move Object Using Physics
      1. Moving Gameobject Using Adding Force
      2. Moving Gameobject Using Velocity
      3. Moving Gameobject using MovePosition
You can check out all the ways and then you can find the best way to move object in unity according to your requirement. Hope you will find your answer here if not feel free to ask your query in the comments below.

A Questions For You

Here are the two questions for you.

  • How do you move gameobject in unity?
  • Which way do you find in this article that you didn’t know before?
  • Or You already knew all of this 🙂

Whatever it is Let me know by leaving a Comment below. Also, feel free to comment with your queries or concerns.

I hope this article was helpful and you may have learned something new today.

Aakash Solanki
Aakash Solanki

I am a professional unity game developer. I have a passion for creating immersive gaming experiences. For me writing articles feels like giving back to the community we have learned from. My hobbies involve playing games and writing articles and sometimes I also create youtube videos.


Share on social media

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top