How can I move my enemy by following my Player position with only 1 coordinate

Viewed 143

i am making a 2d game,i am getting stuck with the part that i want my enemy following my Player with only Y coordinate, it mean if my Player moving up or down, the enemy will following but not move forward. here is my current code in Enemy Script:

if (Vector2.Distance(transform.position,target.position) > 200)
            {
                transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
            }
else
{
// i want my enemy following my player with only Y coordinate right here, not moving forward anymore
}
2 Answers
if (Vector2.Distance(transform.position, target.position) > 200)
{
    transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else
{
    // i want my enemy following my player with only Y coordinate right here, not moving forward anymore
    transform.position = Vector2.MoveTowards(transform.position, new Vector2(transform.position.x, target.position.y), speed * Time.deltaTime);
}

The Vector2 struct has two position components: x and y. To move along the y-axis, create a temporary Vector2 to store the transformed position and copy the y component only.

     Vector2 temporaryPosition = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
     if (Vector2.Distance(transform.position, target.position) > 200)
     {
         //copying the x and y position if the distance is greater than 200
         transform.position = temporaryPosition;
     }
     else
     {
         // copy the x position if the distance is below or equal to 200
         transform.position = new Vector2 (transform.position.x, temporaryPosition.y);
     }

You cand find more documentation about Vector2 here

Related