Search code examples
c#unity-game-engine2d-games

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


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
}

Solution

  • 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);
    }