How do I make an NPC have a "line of sight" or an area in which it can detect a hero and how do I make it act upon it?

From OHRRPGCE-Wiki

Sometimes you want an NPC to be activated from a distance away, for example, a pacing guard who sees your heroes if they step in front of him. There is no built-in "line of sight" or "distance" feature for triggering NPC's, but you can fake the effect with plotscripting.

This article is a simplified version of Scripts:Line of sight, which has more features.


For this example we will write a script that makes a guard NPC do something if you stand in front of him within 8 spaces.

This script must run as a continual loop. Normally you would make it the "map autorun" script for the map the guard is on. This script assumes that the guard is NPC 0. You can easily add more than one NPC, but each NPC must have its own ID number, because the script (temporarily) modifies the 'movetype' in the NPC definition (with the "alter NPC" command).

plotscript, vigilant guards activate, begin 
  variable (this map) 

  this map := current map 

  while (this map == current map) do, begin 
    vigilant guard (0)  #change '0' to the correct NPC ID
    #vigilant guard (1) #repeat as desired
    wait (1)
  end 
end 

script, vigilant guard, NPC ID, begin
  variable (guard) 

  guard := NPC reference (NPC ID)

  variable (x1, x2, y1, y2, dir, dist, start chasing)

  x1 := NPC X (guard)
  x2 := hero X (me)
  y1 := NPC Y (guard)
  y2 := hero Y (me)
  dir := NPC direction (guard)
  
  dist := x2 -- x1
  if (y1 == y2) then (
    if (dir == right && dist <= 8 && dist >= 0) then (start chasing := true)
    if (dir == left && dist >= -8 && dist <= 0) then (start chasing := true)
  )
  dist := y2 -- y1
  if (x1 == x2) then (
    if (dir == down && dist <= 8 && dist >= 0) then (start chasing := true)
    if (dir == up && dist >= -8 && dist <= 0) then (start chasing := true)
  )

  if (start chasing) then ( 
    wait for NPC (NPC ID)
    Alter NPC (NPC ID, NPCstat:move type, NPCmovetype:chaseyoupathfinding) #you can change the NPCmovetype to suite your needs
    Alter NPC (NPC ID, NPCstat:move speed, 5) 
  ) 
end
Revise.png
This article does not meet the standard of quality we would like to have. Feel free to revise it and make it better by using the edit link at the top of the page. This tag should be removed when an editor feels it is of high quality.

This script hasn't actually been tested in a real RPG yet, so I can't consider this article finished until it has been.

Alternative method: You can place a certain number of "step-on" invisible NPCs in front of the guard, but this only works if he is standing still.