Enemy chase player and do not stop until it reaches the target?

Hey, I will get to the point : I have script that makes Enemy move towards my Player (it is 2D platformer). Enemy move if distance between Player and object is less than max dist. but if I reach higher value with my Player than max dist Enemy stops following.

 if (Vector2.Distance(transform.position, Player.transform.position) <= 10)
        {
            Vector2 enemyVelocity = new Vector2((transform.position.x - Player.transform.position.x) * Speed, 0);
            rgBody2d.velocity = -enemyVelocity.normalized * Speed;
            anim.SetFloat("Speed", enemyVelocity.magnitude);

        }

How can I make follow my player if it shows in Camera and do not stop until it reaches the Player?
Anyone who can explain?

In your behavior add the following

void OnBecameVisible() {
  enabled = true;
}

void OnBecameInvisible() {
  enabled = false;
}

If that isn’t sufficient (because the sprite gets hidden when on screen) try checking the sprite’s position against one of the following

  • Screen.width
  • Camera.pixelWidth

@mrpmorris so I got this working for me :smiley:

float leftBorder = Camera.main.ViewportToWorldPoint(new Vector2(0, 0)).x;
        float rightBorder = Camera.main.ViewportToWorldPoint(new Vector2(1, 0)).x;

        if (leftBorder <= transform.position.x && rightBorder >= transform.position.x)
        {
            chasePlayer();
        }
        else
        {
            enemyPatrol();
        }

Thank you very much for help and navigating me!