How to move objects in Unity (3 methods with examples)

Moving an object in Unity can be very straightforward.
It typically involves modifying the properties of an object’s Transform component, which is used to manage a game object’s scale, rotation and position in the world.
However, there are many different ways you can do that…
And while most methods of moving an object in Unity involve modifying the object’s Transform in some way, the exact method you use will vary depending on the type of movement you want to create.
But don’t worry, because in this article, you’ll learn how and when to use each of the different methods for moving an object in Unity, so that you can use the one that’s right for your project.
Here’s what you’ll find on this page:
Let’s get started.
Moving Objects in Unity explained (video)
For a general overview of how to move objects in Unity try my video, or continue to the full article below.
How to move an object in Unity
The most straightforward method of changing an object’s position in Unity is to set it directly, which will instantly move it to a new vector 3 position in the world.
This works by setting the Position property of an object’s Transform component to a new position.
Like this:
Or you can add a vector to an object’s position, to move it by a set amount in a specific direction.
Like this:
Which looks like this:
Adding a vector to an object’s position moves it by that amount.
It’s possible to modify the properties of an object’s Transform from a script that’s attached to it by using the Transform Property:
The Transform property, which is typed with a lower case ‘t’, allows you to reference the Transform component of an object from a script that’s attached to it, without getting a reference to it first.
Which is useful, as it allows you to easily reference, or change, an object’s own position from a script.
Like this:
Modifying a Transform’s position is the most straightforward method of creating movement in Unity.
Either by modifying it directly, over time, or by using the Translate function which allows you to move an object in a specific direction.
How to use Transform Translate in Unity
The Translate function in Unity moves an object by a set amount, relative to its current position and orientation.
Like this:
This is different to simply adding a vector to the object’s position, which would move it relative to world space, while Translate will, by default, move an object relative to its own local space.
This means that, when using Translate, passing in a forward vector will move the object in the direction of its blue axis, the Z-Axis.
When it’s called once, Translate moves an object by a set amount one time.
However, by calling it every frame, it’s possible to create continuous movement.
Like this:
However, there’s a problem with this method.
Because framerates vary between devices and, because each frame often takes a different amount of time to process than the last, the speed of an object’s movement would change depending on the framerate when moving an object in this way.
Instead, multiplying the movement amount by Time.deltaTime, which is the amount of time since the last frame, creates consistent movement that’s measured in units per second.
Like this:
Which looks like this:
Adding a scaled vector over time creates movement.
This works fine, however, it can sometimes be more convenient to manage movement direction and speed separately, by using a Unit Vector to determine the direction and a separate float value to control the speed.
Like this:
This has the same effect as manually typing out the vector, except that the speed is now separate and can easily be changed.
In this example, Vector3.forward is shorthand for (0,0,1) which is the forward direction in world space.
Multiplying Vector3.forward by the speed value, in this case 2, creates the vector (0,0,2) which, when multiplied by Delta Time, creates a forward movement of two units per second.
The result is the same as when manually typing out the vector, except that the speed is now separate and can easily be controlled.
Direction vectors in Unity
A normalised vector, or unit vector, in Unity is simply a vector with a length of 1 that describes a direction. For example the unit vector (0,0,1) describes the forward direction in world space.
Normalised vectors can be extremely useful for calculating distance and speed.
For example, you could multiply a unit vector by 10 to get a position that’s ten units away in a certain direction.
Or you can multiply a vector by a speed value and by Delta Time to create movement at an exact speed in units per second.
While you can type unit vectors manually, you’ll find a number of shorthand expressions for common directional vectors in the Vector 3 class.
For example:
These relate to common directions in world space, however, it’s also possible to get a normalised direction vector relative to an object’s local position and rotation.
Like this:
These can be extremely useful for creating object relative movement.
Such as moving an object forward in the direction that it’s facing.
Like this:
In this case, the object is still moving forward at a speed of two units per second.
The difference is that the direction is based on the object’s orientation, not the world. Which means that if the object rotates, it’ll turn as it moves.
While using a Transform’s local directions can be useful for getting the orientation of a specific object, some functions already operate in local space by default.
Such as the Translate function which, by default, applies movement relative to the object’s local position and orientation, unless you set otherwise.
Which means that, if you use transform.forward with the Translate function, you’ll get a compounded effect, where turning the object throws off its forward vector.
Creating object-relative movement in this way can be useful for adding player controls, where the player can move an object forward, backwards or sideways using input axes, such as from the keyboard.
How to move an object with the keyboard in Unity
To move an object with the keyboard, or with any other input device, simply multiply the direction of movement you want to apply, such as forward, for example, by the Input Axis you want to use to control it.
In Unity, when using the default Input Manager, you’ll find an Input Axis for Horizontal and Vertical movement already set up and mapped to the WASD keys and arrow keys on the keyboard.
- Input in Unity made easy (a complete guide to the new system)
Each axis returns a value between -1 and 1, which means that you can use the value that’s returned to create a movement vector.
Like this:
This allows you to create object-relative movement controls using the keyboard or any other input device.
Which looks like this:
The Horizontal and Vertical input axes can be used to create movement control.
Even movement controls with Clamp Magnitude
When moving an object using horizontal and vertical axes it’s possible to create diagonal movement that is faster than the speed of movement of a single axis.
This is because the length of the vector that’s created from a forward vector of 1 and a sideways vector of 1 is longer than either one on their own, at around 1.4.
Which means that holding forward and right on a keyboard, for example, would move the player 1.4 times faster than just moving forwards or sideways alone, causing uneven 8-way movement.
So how can you fix it?
One option is to normalise the vector, like this:
However, while this does work, it means that the length of the vector is always one, meaning that any value less than one, such as analogue movements, or the gradual acceleration that Unity applies to digital axis inputs, is always rounded up to one, no matter what.
This might not be a problem for your game if, for example, you’re using the Raw Input values and are deliberately creating tight digital controls.
Otherwise, to also support values that are lower than 1, you can limit the length of the vector instead, using Clamp Magnitude.
Like this:
This will limit the length of the vector to one, while leaving lower values intact, allowing you to create analogue 8-way movement that’s even in all directions.
The Translate function creates movement that’s relative to the Transform component that it’s called from.
However, you may not always want to create player-relative movement.
So how can you move an object in a direction that’s relative to a different object, such as the camera, for example?
How to move an object, relative to the camera
It’s possible to move an object relative to the position of the camera in Unity by using the camera’s forward vector in place of the object’s forward vector.
Like this:
Because the movement is relative to the camera’s position, the Relative To parameter in the Translate function needs to be set to World Space for this to work.
However, there’s a problem…
The forward vector of the camera may, in some cases, be facing at an angle, down towards the player, meaning that any movement that’s applied will also push downwards, instead of along a flat plane, as you might expect.
To fix this, you’ll need to manually calculate the direction between the camera and the object, while leaving out any rotation that you want to ignore.
To calculate a direction, all you need to do is subtract the position of the origin from the position of the target and then, normalise the result.
Like this:
To ignore the difference in height between the camera and the object it’s looking at, simply create a new Vector 3 that replaces the camera’s height with the object’s instead.
Like this:
This will return a direction that is looking towards the object, but isn’t looking up or down.
You can then use the corrected direction that’s created to calculate movement that’s relative to the camera on a flat plane.
Like this:
Which looks like this:
You can create camera relative movement by using the camera’s forward direction in place of the object’s.
By understanding the relative direction of an object, it’s possible to create any kind of movement control that you want.
However, a lot of the time, you may want to move an object in a different way, that’s not directly controlled by the player.
For example, moving an object to a set position or towards another object.
How to move an object to a position in Unity
Generally speaking, there are two different ways to move an object into a specific position.
- By speed, where the object moves towards a target at a specific speed,
- By time, where the movement between the two points takes a specific amount of time to complete.
The method you use will depend on how you want to control the object’s movement, by time or by speed.
Here’s how both methods work…
How to move an object to a position at a set speed (using Move Towards)
It’s possible to move an object towards another object or a specific position in the scene using the Move Towards function.
Move Towards is a function of the Vector 3 Class that will modify a Vector 3 value to move towards a target at a set speed without overshooting.
Which works great for moving an object towards a position in the world at a speed you can control.
Like this:
The movement can also be smoothed, by using the Smooth Damp function, which eases the movement as it starts and ends.
Like this:
This works by setting the position of the object to the Vector 3 result of the Smooth Damp function, passing in a target, the current position and a reference Vector 3 value, which the function uses to process the velocity of the object between frames.
This can be useful for smoothed continuous movement, where the target position may change from one moment to the next such as when following the player with a camera.
Such as in this example of a smooth camera follow script using Smooth Damp:
In this example, the camera will smoothly move towards the player and turn to face them, while keeping at a height of 3 units and trying to stay at a distance of 5 units away.
Move Towards works great as a way to move an object towards a position dynamically.
This is because the movement is speed-based, and can be controlled even if the target position moves or is unknown.
However, there are many times where you may simply want to move an object to a known position over a set period of time.
Such as moving a platform, or opening a door.
So how so you create time-based movement in Unity?
How to move an object to a position in a set time (using Lerp)
Lerp, or Linear Interpolation, is used to find a value between a minimum and maximum based on a position value, ‘t’, which is a float between zero and one.
The value that’s returned depends on the value of t where, if t is 0 the minimum value is returned, while 1 returns the maximum value.
Any other value in-between 0 and 1 will return a representative value between the minimum and maximum ends of the scale.
Typically, Lerp is used to change a value over a period of time, by incrementing t every frame to return a new value on the scale.
This can be used to change a colour, fade an audio source or move an object between two points.
- The right way to use Lerp in Unity (with examples)
It works by passing in the amount of time that has elapsed during the Lerp, divided by the total duration. This returns a 0-1 float that can be used for the t value, and allows you to control the length of the Lerp movement by simply choosing how long you’d like it to take.
Like this:
Vector3.Lerp works in the same way except that, instead of returning a float, it returns a point in the world between two others, based on the t value.
This can be useful for moving an object between two different positions, such as a door with an open and closed state.
Like this:
In this example, I’ve used a coroutine to move the door object up by a set distance from the door’s starting position, whenever the Operate Door function is called.
Which looks like this:
Lerp can be used to move an object between two states, such as the open and closed positions of a door.
This creates a linear movement from one position to another, however, it’s also possible to smooth the Lerp’s movement using the Smooth Step function.
This works by modifying the t value with the Smooth Step function before passing it into Lerp.
Like this:
This will ease the movement of the object at the beginning and end of the Lerp.
How to move an object to a position using animation
Depending on how you’d like to control the movement of objects in your game, it can sometimes be easier to simply animate the object you’d like to move.
This typically involves modifying properties of an object and storing them in Keyframes, which are then smoothly animated between over time.
For example, you could use animation to move an object between two points, such as a floating platform.
This would need three Keyframes to work, one for the starting position, another for the platform’s end position and a final Keyframe to return the platform to its original position, looping the animation.
To animate an object you’ll need to add an Animator and an Animation Clip, which you can do from the Animation window.

Next, select a position on the Animation Timeline, this will be the position of the 2nd Keyframe, when the platform is furthest away..

Assuming that, at zero seconds, the platform is at its starting position, this will be the halfway point of the animation which, in this case, is 5 seconds.
Next, enable Keyframe Recording by clicking the record button:

While Keyframe Recording is enabled, any changes you make to an object will be saved to a Keyframe at that timeline position, such as changing its position:

Create a final Keyframe at ten seconds, setting the object’s position to its original values to complete the animation (remembering to disable Keyframe Recording when you’re finished).

The end result is a platform that moves smoothly, and automatically, between its Keyframe positions.
These methods work well for creating controlled precise movements in Unity.
But, what if you don’t want to control an object’s movement precisely?
What if you’d rather push, pull or throw an object, to create movement using physical forces instead?
How to move an object using physics
Most rendered objects in Unity have a Collider component attached to them, which gives them a physical presence in the world.
However, an object with only a Collider is considered to be static, meaning that, generally speaking, it’s not supposed to move.
To actually move an object under physics simulation, you’ll also need to add a Rigidbody component to it, which allows it to move, and be moved, by physical forces, such as gravity.
You can also move a physics object by applying force to its Rigidbody using the Add Force function.
Like this:
This works in a similar way to the Translate function except that the vector you pass in is a physical force, not a movement amount.
How much the object moves as a result will depend on physical properties such as mass, drag and gravity.
There are two main ways to apply physical force on an object.
You can either apply force continuously, building momentum and speed over time, or all at once in an impulse, like hitting an object to move it.
By default, the Add Force function applies a continuous force, like a thruster gradually lifting a rocket.
Like this:
Notice that I’ve used Fixed Update, and not Update, to apply the force to the object.
This is because Fixed Update is called in sync with the physics system, which runs at a different frequency to Update, which is often faster and can vary from frame to frame.
Doing it this way means that the application of force is in sync with the physics system that it affects.
Alternatively, you can also apply force in a single burst, using the Impulse Force Mode.
Like this:
This will apply an amount of force to an object all at once:
Add Force can be used to push objects gradually, or apply force in a single hit, like this.
Which can be useful for faster, more explosive movements, such as making an object jump.
How to move a Rigidbody (without using force)
Normally, when you’re moving an object using physics, you might typically apply force to move it around in a realistic way.
But, what if you want to use the physics system but you want to move the object directly, in the same way as moving it using its transform component?
It’s possible to do this by using the Move Position function, which is a rigidbody method that will move an object to a precise position in a similar way to setting its transform position.
Like this:
This is slightly different to setting the rigidbody’s position value directly, which effectively teleports an object to a new position using its rigidbody.
The Move Position function, however, while it basically does the same thing, is assumed to be moving the object from one position to the next.
What this means is that, if you’ve enabled interpolation on the rigidbody, its visual position will still be smoothed between the, typically slower, fixed update calls, even though the object is being moved manually and not with forces.
As a result, if you want to change the position of a physics object immediately, to teleport it somewhere else, set its Rigidbody Position value, but if you want to move it, gradually, use the Move Position function instead.
Now it’s your turn
How are you moving objects in your game?
Are you moving them using their Transform components?
Or are you moving them with physics?
And what have you learned about moving objects in Unity that you know others will find helpful?
Whatever it is, let me know by leaving a comment.

by John Leonard French
Game audio professional and a keen amateur developer.
Get Game Development Tips, Straight to Your inbox
Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.
My favourite time-saving Unity assets
Rewired (the best input management system)
Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.
DOTween Pro (should be built into Unity)
An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.
Easy Save (there’s no reason not to use it)
Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.
Comments
Very good article, as always. If I got it when I started with Unity, it would have saved me a lot of time. Thanks for your efforts.
Btw I subscribe to newslleter but don’t get notifications of new articles. Just tips with links to older content. Is it supposed to work this way? I would like to get notifications of fresh articles
Thank you! The newsletter is ordered, so you’ll get a mix of topics including some content that’s not on the site, but if you’re getting content that you’ve already read about I’ll maybe change how that works. Thanks for the feedback.
Your Topics start becoming a references for me,thank you sir for the efforts and please keep posting
Glad it helped! Thank you.
That was very helpful, thank you so much
one frame == about .05 of a second.
transform.position == with an approx average of 3-5 1×1 tiles moved per frame.
transform.Translate == about the same as transform.position.
There is no instant move command with unity that I’m aware of. Unfortunately unity is notoriously well known for being “half baked” like this. However, unity is free, soooo you get what you pay for and shouldn’t complain IMO.
Every movement command just gives you the illusion of an “instant” movement by moving the object super fast and hoping that no one notices.
The best results I’ve been able to come up with is by sticking my transform.position command inside of a while loop. For whatever reason, this reduces the total frames that a GameObject is seen moving from posA to posB by 60% to 80%.
Example 1: Using a normal transform.position command
-If you have to move 300 1×1 tiles on the Y axis and 900 1×1 tiles on the X axis and you do the standard transform. position to move your object (you supposedly get a 1.4 speed boost because its a diagonal movement, i haven’t seen that to be true yet but who knows). Anyways, it will take somewhere around 351 frames to fully move your object that distance.
And during all 351 frames of that movement your GameObject will be teleporting all over and maybe acting goofy depending on what you’ve got going.
Example 2: Placing your transform.position command inside of a while Loop
– Take the same 300 by 900 map and while loop your transform.position and it will only expose your GameObject to the players eyes for somewhere around 15-50 total frames after fully moving your object that same distance. Meaning that players are 60% to 80% less likely to see your moving gameObject.
This is some dirty spaghetti code that i cooked up once as an example.
Although the code is dirty as sunflower seeds, the fact remains that while loops == much cleaner transform.positions. And there is no such thing as a truly bonafide
“instant move command” in Unity as far as I know at this time anyways.
private IEnumerator MovePlayer(Vector3 direction)
<
loopCounter = 0;
print(“START”);
isMoving = true;
float elapsedTime = 0;
origPos = transform.position;
targetPos = origPos + direction;
timeToMove = saveTimer;
while(elapsedTime = 900 || currentPosition.x <= 0 || currentPosition.y = 300)
<
cantClaim = true;
wrappedAround = true;
targetPos = detector.currentPosition;
currentPosition.z = 1;
transform.position = currentPosition;
if(currentPosition.x 0)
<
currentPosition.x = 900 -.1f;
transform.position = currentPosition;
>
else if(currentPosition.y 0)
<
currentPosition.y = 300 -.1f;
transform.position = currentPosition;
>
else if(currentPosition.x < 0 && currentPosition.y 300 && currentPosition.x 900 && currentPosition.y 300 && currentPosition.x > 900)
<
currentPosition.x = .1f;
currentPosition.y = .1f;
transform.position = currentPosition;
>
currentPosition = transform.position;
>
if(currentPosition.x 0)
<
cantClaim = false;
>
if(currentPosition.y > 0 && currentPosition.y < 300)
<
cantClaim = false;
>
print("AFTER = CURRENT POS = " + currentPosition + " / TARGET POS = " + targetPos);
loopCounter += 1;
print("LOOP COUNTING = " + loopCounter);
yield return null;
> //end of while statement
currentPosition.z = -1;
if(wrappedAround = false)
<
targetPos.z = -1;
transform.position = targetPos;
currentPosition = transform.position;
>
if(wrappedAround = true)
<
targetPos = detector.currentPosition;
targetPos.z = -1;
transform.position = targetPos;
currentPosition = transform.position;
wrappedAround = false;
>
wait = 1;
betweenMoves = true;
// isMoving = false;
print("END");
>//END OF move unit
Sorry, but what you’ve said isn’t correct. To address some of the points in your comment:
- Framerate is variable, and unless your game is running at a locked 20fps, frame time isn’t going to be 0.05, it’s going to vary every frame. Which is why you always need to use Delta Time when applying a movement amount
- Changing an object’s position using its transform does essentially teleport it to that position, there’s no behind the scenes movement that I’m aware of.
- The 1.4 diagonal boost you mentioned is to do with the adding up of 2 input axes, where the result is a diagonal vector with a length of 1.4, not 1. It’s usually fixed by normalising the input vector.
- There should be no reason why placing the same function in a while loop changes how it operates. It’ll still be called by Update, or whatever event function you place it in. The only difference is the condition of the while loop.
- In your example, you haven’t scaled your movement by Delta Time. If you’re trying to move an object without Delta Time, you’re going to get inconsistent movement.
I feel like what you’ve done is made something very complicated when it really doesn’t need to be, the simplest way to move an object in Unity is to apply a movement amount, that’s scaled by delta time, every frame. However, if I’ve missed something and you’re having a problem with movement in Unity, then please tell me about it, describe what’s happening that shouldn’t be so that I can understand what you’re experiencing and why.
Please note, however, that this is, very deliberately, not a Unity forum and I have a strict comment policy regarding comments that could be confusing or unhelpful to others.
All the best,
John.
Hi John,
This is very interesting and informative. I am just starting a project where I need to move an object up and down, side ways and also diagonally and I was wondering which method is best to do this and I came across this article. You have explained everything beautifully and saved me a lot of time. I am just a little unsure about how to move diagonally but I think I will get if I read your article a couple of times.
Thank you.
Thank you, I’m so glad it helped. Normalizing a vector that’s made up of the two directions that will make the diagonal (e.g. (1,1,0) for example) should give you the diagonal movement you want. Like this: Vector3 movementAmount = new Vector3(1, 1, 0).normalized;
Thank you and I appreciate your quick reply
Hi John,
Sorry to butt in again.
I am able to get the movement diagonally. I need to move it at various speeds starting from 45 meters/second. Is a unit in Unity equals to 1 meter? So if I use 45 * Time.deltaTime do I get my speed as 45m/sec? What if I wanted to use, say, 300 deg/sec; can the units be changed in Unity?
Thank you.
Vasu
Yes, 1 unit in the world is meant to be 1m (more info) so 45 * delta time is 45m per second. It will also work with rotation, yes, so you can create degrees per second with the same technique.
Really Awesome Work John French. I read your about us and it feels like i am reading mine. but it motivates me a lot. Thank you for such a great contribution.
Excellent information. Thank you.
In my project, for the graphics part, I just need to move alphabets at high speeds from left to right in all directions. No collisions with anything. So I used 2D /sprites/square and put the alphabets on it.
I used every possible move method you have indicated above to move my alphabets (not animations, yet). The alphabets moved smoothly in all directions. No issues.
It works fine for low speeds but once I use speed 30 and above, instead of one alphabet moving across the screen, it doubles( I am sorry I don’t know the name for this: doubling, bunching, lagging or some such thing) and moves across the screen. For example, instead of just one image(in this case letter ‘C’) going from left to right, it goes as below in bunches, from left of the screen to the right.
Thinking that it might be an issues with my monitor, I tried different devices but this behavior persists across all of them.
Much appreciated if you could show me a way to overcome this bizarre movement behavior.
It sounds like a visual problem but I don’t know that for sure. If you don’t mind sharing your code email [email protected] and I will take a look.
Thank you. I just emailed the code and a screenshot of the issue.
This is such an informative and clearly explained article, what an excellent overview.
I had become quite confused with all the different ways to move objects in Unity, and here it’s all made perfectly clear.
Thank you very much. I’ve bookmarked it and will subscribe to your newsletter!
Thank you! I’m so glad it helped.
Great article, found it really helpful thanks. One question, with the physics movement, is it possible to move an object to a target position as well?
Not that I know of, no. I don’t think there’s a Physics version of Move towards for example. One option might be to use Add force in the direction of a target position and while the position of the rigidbody is not close enough to the target point.
Brilliant. Fantastic article. Thanks a lot for this. Really helpful!
You’re welcome Cesar!
Thanks for an awesome article on the topic of moving objects!
Feel free to delete this if it confuses others, but somehow I still managed to not get the thing I wanted to do to work.
So I want to attach a script to any object in my scene and have it move towards the camera (in this case the player/first person view). I get the dreaded nullreference exception: Object reference not set to an instance of an object when running the code(it compiles, the target.position = ….. gets the nullreference). Why?
public class MoveTowardsPlayer : MonoBehaviour
<
// Adjust the speed at which object is moved towards the camera / player
public float speed = 10.0f;
// Initialize target with transform class
private Transform target;
// Start is called before the first frame update
void Start()
<
// Update is called once per frame
void Update()
<
var step = speed * Time.deltaTime;
target.position = Camera.main.transform.position;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
// Display positions to help with debugging
Debug.Log(“Camera target position is” + target.position);
>
>
Sorry for being a noob, perhaps this helps someone else too.
Best regards,
Ron
Hi Ron! From here it looks like you’re using an empty Transform component. Transform is a reference variable, not a value, so target in your script needs to relate to a real object, which doesn’t seem to be how you’re using it. You can probably remove the target alltogether, and just use the camera’s position directly, or change your target variable to a Vector 3 value instead of a transform. e.g. target = Camera.main.transform.position;
Hope that helps!
The article was great. I learned a lot. Thanks for this. However, I have one question. I want the Particles I created with Particle System to go from one point to another and I want it to do it at a certain speed. But it either doesn’t move to the position I gave it at all or it goes very fast, it seems like it’s teleporting.
Lerp Function : Unity
In game development, one of the most common problems is the smooth transition of objects from one position to another. A linear interpolation or Lerp function is a popular technique used to achieve this in Unity. In this blog post, we will explore the lerp function in Unity and its implementation.
What is Lerp Function?
The Lerp function stands for linear interpolation .
The function returns a value that is a linear interpolation between the starting and ending values, based on the weight parameter. It takes three arguments:
- The starting value
- The end value
- A weight between 0 and 1 representing the percentage of the value between the start and end values.
In case of linear transformation, the Lerp function calculates the position along the line that corresponds to the input value. When the input value is 0, the function returns the starting position, and when the input value is 1, it returns the target position. For values between 0 and 1, it returns a position that is between the two endpoints.
Implementation of Lerp Function
Unity provides a built-in Lerp function that can be used to interpolate between two positions. The function is called Lerp and can be called using the following syntax:
This function takes the startingPosition , targetPosition , and a value t between 0 and 1 representing the percentage of the distance between the two positions. It returns the position that is t percent of the way from the starting position to the target position.
Transform example using Lerp function
Suppose we have an object that we want to move from its current position to a new position over a period of 2 seconds. We can use the Lerp function to achieve this by calculating the position of the object at each frame using the following code:
In this example, we store the target position in the target variable and the speed at which we want to move the object in the speed variable.
In the Start function, we calculate the distance between the current position of the object and the target position and store it in the journeyLength variable.
In the Update function, we calculate the distance covered by the object at each frame using the distCovered variable. We then calculate the fraction of the journey completed using the fracJourney variable. Finally, we use the Lerp function to move the object from its current position to the target position based on the fraction of the journey completed.
Smooth camera movement using Lerp function
Suppose we have a camera in ourr game that follows the player’s movements. we can use the Lerp function to smoothly interpolate between the camera’s current position and the player’s position, creating a smooth camera movement effect.
fractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.
Color Transition using Lerp function
We can use the Lerp function to create smooth transitions between different colors. For example, suppose we want to change the color of a material over time. we can use the Lerp function to smoothly interpolate between the current color and the target color.
fractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.
Interpolation between values using Lerp function
The Lerp function can also be used to interpolate between different values, such as floats or integers. For example, suppose we have a variable that represents the player’s health. we can use the Lerp function to smoothly interpolate between the current health value and the target health value.
fractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.
Conclusion
The Lerp function is a versatile and powerful tool in Unity that can be used to create smooth animations and transitions. By understanding how the function works and experimenting with different parameters, we can create a wide variety of effects in our game.
Lerp функции в Unity (C#)
DailyDev

В этом посте я хочу рассказать про принцип работы Lerp функции в Unity. Данная функция невероятно полезна, так как именно с её помощью мы можем сделать плавное перемещение объекта. Как вы уже поняли, я буду использовать язык C#.
Немного теории
Итак, начнем с того, что данная функция может принадлежать различным классам или структурам, в зависимости от того с чем мы работаем. К примеру, Lerp функция присутствует в структуре Mathf которая отвечает за все математические функции представленные библиотекой UnityEngine. Функция принимает аргументы a, b и t каждый из которых имеет тип float, а возвращает функция число типа float. Параметр t принимает значения от 0 до 1.
Описание функции в Visual Studio
Чтож, по определению, функция Mathf.Lerp() — это линейная интерполяция. Что это значит? По сути, это нахождение промежуточного значения, которое получается исходя из тех значений, которые мы передали функции. Покажу более наглядно.
Предположим, что мы передаем функции аргументы: a = 0, b = 1, t = 0.3f. Нашим начальным значением будет являться число a, а конечным b, иными словами, мы рассматриваем отрезок [a, b]. Что же делает параметр t? Этот параметр говорит нам какое число мы возьмем на этом промежутке. В данном случае это будет выглядеть так:

Иными словами, мы берем отрезок за 1 и возвращаем число которое делит его на отметке 0.3. Но как мы можем использовать это на практике? С помощью этой функции мы можем задать плавное перемещение объекта из одной точки в другую. Постепенно приближаясь к цели, объект замедляется.
Реализация
Рассмотрим использование этой функции на практике. Зададим движение кубу.
В данном случае мы будем использовать функцию структуры Vector3, так как мы работаем с transform.position.
Реализация движения куба:
Каждый кадр куб проходит от своего положения до цели примерно треть пути, и, так как начальное значение параметра a каждый кадр разное, то и получается, что куб замедляется приближаясь к цели.
Заключение
В этом посте рассмотрел лишь основные способы использования данной функции, для более глубокого понимания я оставлю полезные ссылки.
Unity Fundamentals — Moving a game object
Understand transform position and learn simple methods on how to move game objects in Unity.
![]()
![]()
Resources
Basics first
Each object in Unity holds Transform. Transform is responsible for position, rotation, and scale manipulation of the object.
Each object placed in the Unity scene has some initial position, rotation, and transform.
The object is residing either in 3D or 2D space, depending on the type of the project. In our case, we will be working on a 3D project.
Let’s take a look at the example of a Capsule object located in 3D space.
The Center of the plane is located at the position (0,0,0) whereas the point in 3d space is determined by 3 values laying on the (X, Y, Z) axis.
Each position on the axis holds a different value. Starting from the center position (0,0,0) going to the right is increasing X value, going upwards Y value is increasing and lastly going forward Z value is increasing. Going in the opposite direction of the mentioned axis causing a decrease of the value.
In order to find a point in 3D space you need to know all 3 coordinates, (X, Y, Z)
Now let’s see where Capsule would be located at the position (1,1,1)
The Capsule is now located exactly 1 Unity meter on X-axis, 1 meter on the Z-axis, and 1 meter up on Y-axis. Maybe, you are asking the question “Why is the capsule 1 meter on Y?”
Well, the Capsule object has 2 meters, so the center of the capsule is 1 meter above the ground.
That’s why it needs to be placed 1 meter on the Y-axis. Otherwise, it would be half-way body in the middle of the plane.
Change position in the code
You can change the object position in the code by manipulating the transform property of the object.
The position is represented internally by the struct called Vector3. Vector3 holds 3 values -> x,y,z
Let’s move the game object to the position (1,1,1)
That’s are the basics you need to know about the position. Remember position is a location in the space represented by the (X, Y, Z) value, each laying on its own axis.
Now we are going to create a functionality to move the Capsule when a player is pressing input keys on the keyboard.
Movement script
First, create a new script called Movement.cs and add it to the Capsule object.
We will place movement functionality into the Update method. Update is executed during the entire play-time of the game — how often depends on the frame-rate of your game.
About Update
The Update method is called once per frame.
If the game is running at 140fps then Update is called 140 times per second. This is making it a great spot for functionality that should happen constantly during the game duration.
Handling player input is usually a functionality that is placed in the Update method.
Capture a player input
In order to move a game object, we need to capture a player input. If a player is using as the input device a keyboard, we want to capture as he is pressing arrow keys or AWSD keys on the keyboard.
For this purpose, we can write the following code in Update.
Input values are usually values in the range between -1 and 1. Try it out.
Horizontal Axis
Horizontal value of 0 means that NO “movement” key is pressed.
Value 1 means that the player is pressing the “right” arrow or “D” key (player wants to move right)
Value -1 means that the player is pressing the “left” arrow or “A” key (player wants to move left)
Vertical Axis
Vertical value of 0 means that NO “movement” key is pressed.
Value 1 means that the player is pressing the “up” arrow or “W” key (player wants to move forward)
Value -1 means that the player is pressing the “down” arrow or “S” key (player wants to move backward)
To get from 0 to 1 or 0 to -1 value while the user is holding down movement keys, will not happen immediately, but with default settings of Unity, it will happen super-fast!
So while holding “right” arrow for one second you can get values in horizontal input, 0, 0.1, 0.3, 0.5, 0.7, 1, 1, 1, 1….reaching 1 value almost imidiately.
These are just illustrational values, you can get completely different ones.
Since we can capture the player input we are almost ready to move.
Ready to move
Let’s extend the current implementation.
You will notice one thing. We are moving too fast.
First, let’s explain the code above.
We are storing the vertical and horizontal values in the Vector3 structure, in order to apply them to change the game object position.
As I mentioned before, every game object has a position represented by (X, Y, Z) value.
We need to apply this change of position in form of Vector3 and then provide it to the Translate method. The Translate method will move a game object in direction and distance of translation.
Imagine these 3 cases:
The object will move right when a player is holding the “right” arrow or “D” because Vector3 is holding value (1,0,0), which expresses a change in direction on X-axis.
The object will move forward when a player is holding the “up” arrow or “W” because Vector3 is holding a value (0,0,1), which expresses a change in direction on Z-axis.
The object will move diagonally when a player is holding the “up” arrow or “W” at the same time as the “right” arrow or “D” key, because Vector3 is holding value (1,0,1), which expresses a change in direction on X and Z axis.
These changes are applied to the game object’s current position. You can think of the game object as the center of the plane.
Why is the object moving fast?
The game object is moving fast because Update is called many times per one second. Imagine stable frame-rate(FPS) to be 50. 50 FPS means that your game is updated 50 times per second therefore Update is called 50 times per second.
This also means that holding input keys for the length of 1 second would result in 50 executions of
so if Vector3 would be (1,0,0) then I would move each second 50 meters to the right because Update is called 50 times per second.
Our functionality is frame-dependent. In order to move only 1 meter per second, we need to decrease the value of the movement.
Time delta
First, update translate like this
If you will play the game now you will notice that movement is fixed and you are moving nice and slowly.
Time delta is the completion time of the last frame in seconds.
Again, imagine stable frame-rate 50 frames per 1 second. Completion time of each frame would be 0.02 second because 50 * 0.02 = 1 second
If you multiple the movement by 0.02 you will lower its value, if this happens 50 times per second then Vector3(0,0,1) will apply movement of 1 meter per second.
Now the functionality of the movement is time-dependent. You will use Time.deltaTime a lot.
Final improvements
If the movement is too slow then multiple the movement with some higher value. Let’s say you want to move the Capsule to move 6 meters per second.
Now the final code.
You can notice I called Normalize method on movement. In the case of diagonal movement, you will move faster. Normalize will “fix” it and movement will be the same in every direction.
I am explaining Normalize in much more detail in my other Youtube video: https://www.youtube.com/watch?v=oCU8Ew1XTbs&t=3s
Recap
Now you should have a basic understanding of how to move a game object in Unity. Everything is just about the change of the position over some time-interval.