How can I make enemies start moving only when they are in view of a Camera2D attached to a Player.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jackson King

As the question says, I would like to make enemies start moving only when they are in view of a Camera2D attached to the Player.

:bust_in_silhouette: Reply From: LemonSqueezy

I don’t have any proper code to provide, but the way I would approach this is to add a RayCast2D node to the enemies and cast the ray from the enemy to the player. If the ray collides with the player trigger an action (in this case start moving).

something like:

# code inside enemy

_physics_process():
      $ray.cast_to(PLAYER_COORDINATES)
      $ray.force_raycast_update()
      if $ray.is_colliding() && $ray.get_collider() == PLAYER_NODE:
            # start moving