Moving an Object to a random position

Hi

I was trying to move an object to a random X position not to teleport

the code:
void Update ()
{
timer += Time.deltaTime * timerSpeed;

		rand = Random.Range (-4.5f, 4.5f);

		if (timer >= timeToMove){

			newPosition = new Vector3 (rand, transform.position.y, transform.position.z);

			transform.position = Vector3.Lerp(transform.position, newPosition, speed);

				timer = 0;
		}

and I tried this too :

void Update ()
	{
		timer += Time.deltaTime * timerSpeed;

		rand = Random.Range (-4.5f, 4.5f);

		if (timer >= timeToMove){

			newPosition = new Vector3 (Mathf.Lerp (transform.position.x, rand), transform.position.y, transform.position.z);

			transform.position = newPosition;

				timer = 0;
		}

and tried using (Lerp, SmoothStep) on both and still it teleports to the position

and is there a way to do that in the animator

can use some help please
and thanks :smiley:

You have to add Time.delta time like this:

transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * speed);

Thats it

Calling Random.Range() in update will cause a random value to be called every frame. You dont want that. You want it to be called only once.

    public float speed = 2.0f;
    public float xPos;
    public Vector3 desiredPos;
    void Start()
    {
        xPos = Random.Range(-4.5f, 4.5f);
        desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
    }

    void Update()
    {
        timer += Time.deltaTime * timerSpeed;
        if (timer >= timeToMove)
        {
            transform.position = Vector3.Lerp(transform.position, desiredPos, Time.deltaTime * speed)
            if (Vector3.Distance(transform.position, desiredPos) <= 0.01f)
            {
                xPos = Random.Range(-4.5f, 4.5f);
                desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
                timer = 0.0f;
            }
        }
    }

How can i complete the script, from the begining?

    public float speed = 2.0f;
     public float xPos;
     public Vector3 desiredPos;
     void Start()
     {
         xPos = Random.Range(-4.5f, 4.5f);
         desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
     }
 
     void Update()
     {
         timer += Time.deltaTime * timerSpeed;
         if (timer >= timeToMove)
         {
             transform.position = Vector3.Lerp(transform.position, desiredPos, Time.deltaTime * speed)
             if (Vector3.Distance(transform.position, desiredPos) <= 0.01f)
             {
                 xPos = Random.Range(-4.5f, 4.5f);
                 desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
                 timer = 0.0f;
             }
         }
     }