movetowards 2d unity code example
Example 1: unity movetowards
float speed;
Vector3 goalPosition;
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, goalPosition, speed * Time.deltaTime); //goes from the position of the gameObject to the goalPosition in a strait line with a speed of "speed"
//Also works with Vector2
}
Example 2: unity movetowards 2d
/// <summary>
/// Move 2D sprite towards target
/// </summary>
/// <param name="target"></param>
/// <param name="movementSpeed"></param>
private void Move(Vector3 target, float movementSpeed)
{
//Move
transform.position += (target - transform.position).normalized * movementSpeed * Time.deltaTime;
}