# How to smoothly move object with RectTransform?

Hello! I am new to Unity and don’t understand why I cannot find an easy way to smoothly move a gomeObject a little bit to the left.

I want to move a button which for some reason does not have Transform component, but it has Rect Transform component([77716-снимок.png|77716])

All I need is to change Pos X value to ‘-42’, but I don’t know how.
I am trying this:

Vector3 newPos = new Vector3(-42, 0, 0);
faceButton.transform.position = Vector3.Lerp(faceButton.transform.position, newPos, Time.deltaTime * 2.0f);

But it moves the button to position (-58.9, 24.48, 0) and it happens immediately
So I am pretty confused. Could anyone help please?

Thank you.

@punkrockchicken

When you using Lerp you must know that last parameter is normalized (Max value should be equal 1).
We end moving when we reach 100% our way. Beginning position is equal to 0 and ending position is equal to 1.
You can you set this for example like this:

float timeOfTravel=5; //time after object reach a target place
float currentTime=0; // actual floting time
float normalizedValue
RectTranform rectTransform = GetComponent<RectTransform>(); //getting reference to this component

IEnumerator LerpObject(){

while (currentTime <= timeOfTravel) {
currentTime += Time.deltaTime;
normalizedValue=currentTime/timeOfTravel; // we normalize our time

rectTransform.anchoredPosition=Vector3.Lerp(startPosition,endPosition, normalizedValue);
yield return null; }}

What happen if we have normalizedValue greater then 1? We go further and miss endPosition.

How to run Coroutine?
First cache it with IEnumerator cachedCoroutine =LerpObject();
Next use StartCoroutine(cachedCoroutine);
With coroutine this will move smoother.

Why I used rectTransform.anchoredPosition?

If you use transform at different resolution you will have different position in UI.
AnchoredPosition is always in the same position even if we change resolution.
In UI element we using ratio not actual position of element(that why we have hooks).

(If you use Canvas (Component) - Render mode - World Space - you should use transform.position like normal. In other Canvas modes use this.)

I just tested a piece of code for this. Hope this will help you.

//Declare RectTransform in script
RectTransform faceButton;
//The new position of your button
Vector3 newPos = new Vector3(-42, 0, 0);
//Reference value used for the Smoothdamp method
private Vector3 buttonVelocity = Vector3.zero;
//Smooth time
private float smoothTime = 0.5f;

void Start()
{
//Get the RectTransform component
faceButton = GetComponent<RectTransform>();
}

void Update()
{
//Update the localPosition towards the newPos
faceButton.localPosition = Vector3.SmoothDamp(button.localPosition, newPos, ref buttonVelocity, smoothTime);
}