Question about moving an object technique

So i’m trying to move my player specific amount of units in a direction. Let’s say i want to move my cube to the right with 2 units but, i want it to slide it to that position, not to teleport. I’ve tryied several methods but my player just teleports and i don’t want that. I’m guessing that i should use the Lerp function but i don’t really know how it works.

using UnityEngine;
using System.Collections;

public class cube : MonoBehaviour {
    Vector3 tag;
    int speed = 2;

	// Use this for initialization
	void Start () {
        tag = new Vector3(transform.position.x + 2, transform.position.y, transform.position.z);
    }
	
	// Update is called once per frame
	void Update () {
            transform.position = Vector3.MoveTowards(transform.position, tag, speed * Time.deltaTime);
	}
}

@dxddda4 you can also use Lerp instead of MoveTowards in the same way. Diffrence is that Lerp will slow down approaching target.

You can use the following coroutine. Call it with

StartCoroutine( MoveObjectToPosition( transform, target_position, 1.0f) );

Code:

IEnumerator MoveObjectToPosition( Transform trans, Vector3 end_position, float duration )
{
  Vector3 start_position = trans.position;
  float elapsed = 0.0f;
  while( elapsed < duration )
  {
    trans.position = Vector3.Lerp(start_position, end_position, elapsed / duration );
    elapsed += Time.deltaTime;
    yield return null;
  }
  trans.position = end_position;
}

Alternatively check out the free assets LeanTween or iTween which do the same and much more.

use doTween… here