• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

What would the easiest way to make an enemy follow you only if they see you?

Baller20

Member
I would like to have an enemy move towards you only if you are in their line of sight. Like if I was behind a wall, they wouldn't follow me but if I turned the corner they would start following me. I'm a noob and I don't know how to make this happen. Can someone help me or at least explain how I would work this out? The game I'm making is a top-down style game.
 
T

TheForeman847

Guest
Check out collision_line(). You can use it to check for an object between two points. For example, check for a wall object between the player and the enemy.
 
O

ObserverOfSin

Guest
Step event:
GML:
image_angle = direction
  
if (!collision_line(x,y,player_obj.x,player_obj.y,obj_wall,0,0)) //// checks if there is no collision of obj_wall from x,y, to player_obj x,y
{
dir = point_direction(x,y,player_obj.x,player_obj.y)                /// sets variable dir as direction from x,y to player x,y
if    (dir>direction-fov and dir<direction+fov)                  /// checks if player is within a field of view of 'fov'  
     xor
      (dir+360>direction-fov and dir+360<direction+fov)
     xor
      (dir-360>direction-fov and dir-360<direction+fov)

   {
   move_towards_point(player_obj.x,player_obj.y,1)                       /// moves towards player_obj at a speed of 1
   } 
}
else
{
speed = 0   //// go back to patrolling or whatever
}
You'd need to set 'fov' and 'dir'
 

Nocturne

Friendly Tyrant
Forum Staff
Admin
GML:
if    (dir>direction-fov and dir<direction+fov)                  /// checks if player is within a field of view of 'fov' 
     xor
      (dir+360>direction-fov and dir+360<direction+fov)
     xor
      (dir-360>direction-fov and dir-360<direction+fov)
This can be condensed down to:
GML:
if abs(angle_difference(dir, direction)) < fov // Angle_difference arguments might need reversed... I always get them in the wrong order... :P
{
// Do something
}
:)
 

rytan451

Member
GML:
if abs(angle_difference(dir, direction)) < fov // Angle_difference arguments might need reversed... I always get them in the wrong order... :P
{
// Do something
}
Since the angle_difference is inside abs, the order of the arguments isn't important. abs(a - b) = abs(b - a) after all. Also, the way that I remember the argument order for angle_difference is that a + angle_difference(b, a) is equivalent to a mod 360.
 
Top