Tutorial: Proximity Detection
Difficulty: Intermediate
RPG Maker: 2000/2003
Author: Kentona

This simple tutorial will show you how to code a parallel event that detects whether or not the hero comes within a specified radius relative to the center of the event.

This detecting event can be used in a number of situations, including (but not limited to) monster movement AI, detecting traps, NPC movement or finding hidden items.

The code itself is based on simple circle geometry.

You need:
3 Variables
1 Event

Steps:
1. Create a new event
2. Set the event as a Parallel Process
3. Create 3 Variables: LocationX and LocationY and Radius
4. Insert this code in the event's code window:

<> LocationX: Set, This Event X Coord.
<> LocationY: Set, This Event Y Coord.
<> LocationX: -, Hero X Coord.
<> LocationY: -, Hero Y Coord.
<> LocationX: *, V0001 LocationX
<> LocationY: *, V0002 LocationY
<> LocationX: +, V0002 LocationY
<> Radius: Set, 5
<> Radius: *, V0003 Radius
  : Branch If LocationX is V0003 Radius Less/Equal
     : <> COMMENT: Hero is within a radius of 5 of the event
     : ~insert your code here~
  : Else Handler
     : <> COMMENT: Hero is outside of the radius
     : ~insert your code here~
  : End
The formula is:
(X_event - X_hero)2 + (Y_event - Y_hero)2 <= Radius2

I arbitrarily used 5 as my test radius, but it can be set to whatever you prefer. The event will "trigger" when the hero comes within 5 tiles of the event in a rough circle around the event.

Expanding on this concept:
For monster AI, you could have your code inside of a monster's event, and if the hero comes within the monster's detection radius, have him start running towards the hero. The same idea can be applied to NPCs.

For an Awareness type ability, the event can be set as invisible to start with, but once within the radius the code can change the event's graphic to indicate that an item/object is found. For traps, you could implement a trap difficulty variable.

For example, say the Hero has an Awareness ability of 5, and the Trap's difficulty is 3. In the above code, you could change it so that the Radius varible is set to the Hero's awareness minus the Trap's difficulty:

<> Radius: Set, V0004 Hero's Awareness
<> Radius: -, 3
<> Radius: *, V0003 Radius
...etc...
So now the Hero has to come within 2 tiles to detect the trap. If the Trap's difficulty is greater than the Hero's Awareness, set the Radius to zero:
<> Radius: Set, V0004 Hero's Awareness
<> Radius: -, 8
: Branch If Radius Less Than 0
 : <> Radius, Set 0
: End
<> Radius: *, V0003 Radius
...etc...
Conclusion
Happy detecting and thanks for reading!


Click to Return to the Tutorials Page