Event ID of Nearest Event to Player (RMMV)

I'm wondering if anyone knows of a way to get the event ID of the nearest event to the player in RPG Maker MV? I have been searching various forums for a while now and can't find anything for MV, only VX and Ace. I need to be able to store an event's ID in a variable for whichever event is closest to the player so I can have them be a target.

If anyone knows of a JS snippet or a plugin, that would be very helpful! Thank you!
Care to link to the solutions for VX and Ace? It probably wouldn't take a lot of effort to convert.

Are you wanting any kind of filter? I don't imagine you want transfer events or map animation events (like smoke from a chimney, a critter walking around) to be "targets"?
I'm wondering if anyone knows of a way to get the event ID of the nearest event to the player in RPG Maker MV?

I need to be able to store an event's ID in a variable for whichever event is closest to the player so I can have them be a target.

If anyone knows of a JS snippet or a plugin, that would be very helpful! Thank you!

This should work as needed 🙂
CTB_NearestEventMV Plugin: Click Here to Download

Use the following script call to get the nearest event to the player:
JavaScript:
$gameMap.nearestEvent()

To get the Event Id would be
JavaScript:
$gameMap.nearestEvent()._eventId

However as Shaz mentioned this version does not filter anything... so it will do this with every event.
(Going to go add filter options now)

Edit: Filter options now added too 😉

To use with a filter use like this:
Place a notetag such as <target> into an events notebox then...

Spoiler: Example screenshot of Notetag
1662259705857.png

Use the following script call to get the nearest event to the player:
JavaScript:
$gameMap.nearestEvent('target')

To get the Event Id would be
JavaScript:
$gameMap.nearestEvent('target')._eventId

Now though something else to keep in mind is that if more then one event have the same equivalent distance to the player this will return only one event, that will be the event with the larger id.
(example event #1 is 2 tiles above the player and event #2 is 2 tiles to the left of the player)

... I might go see if I can also create another function to return an array to give multiple events in such situations. idk about that yet.. haven't decided on that yet lol :popcorn:

Edit:
another function to return an array to give multiple events in such situations
Yep basically did that now too 😉

Examples:
JavaScript:
$gameMap.eventsByDistance()
JavaScript:
$gameMap.eventsByDistance('target')

That will return a list of events and sort them by the distance from the player.
Example:
JavaScript:
var events = $gameMap.eventsByDistance('target');
events[0]._eventId // first closest
events[1]._eventId // second closest
events[2]._eventId // second closest
// ...etc

Edit:
v1.21 Added yet another function call to simplify getting event ids.
Example:
JavaScript:
$gameMap.eventIdsByDistance('target')
This returns a array (list) of event id's sorted from the closest to the farthest to the player.

Well hopefully that helps ☺️
Seems like that should do what you need. :popcorn:
Holy crap, some awesome replies! First of all, thank you both @Shaz and @ct_bolt for responding, I really appreciate it!

@Shaz here are the two forum posts I found for VX Ace to set nearest eventID to a variable:
Post 1 — Post 2

And thank you so much for the awesome plugin, @ct_bolt! It looks like in my testing, it is technically working exactly how it should! Unfortunately, it looks like one of the scripts I'm needing to use in my game doesn't want to play nice and it's incompatible with it.

I'm using Hudell's Custom Events plugin to make copies of an event so I don't have to manually copy and paste hundreds of events every time an enemy spawns, but it looks like when that happens via script call those newly spawned events don't get an eventID. Or if they do it's not in the conventional method, so it doesn't actually view them as events that are close to the player.

Oh well, it's not the end of the world. I'll DEFINITELY be using your NearestEvent plugin for other things, because I've wondered if it was possible in other scenarios but never thought to ask about it lol! Thank you again for all your help! It is greatly appreciated!!
Holy crap, some awesome replies! First of all, thank you both @Shaz and @ct_bolt for responding, I really appreciate it!

And thank you so much for the awesome plugin, @ct_bolt! It looks like in my testing, it is technically working exactly how it should! Unfortunately, it looks like one of the scripts I'm needing to use in my game doesn't want to play nice and it's incompatible with it.

I'm using Hudell's Custom Events plugin to make copies of an event so I don't have to manually copy and paste hundreds of events every time an enemy spawns, but it looks like when that happens via script call those newly spawned events don't get an eventID. Or if they do it's not in the conventional method, so it doesn't actually view them as events that are close to the player.

Oh well, it's not the end of the world. I'll DEFINITELY be using your NearestEvent plugin for other things, because I've wondered if it was possible in other scenarios but never thought to ask about it lol! Thank you again for all your help! It is greatly appreciated!!

Very much welcome ☺️

Re-wrote & adjusted/optimized & added support for Hudell's Custom Events. 😉

v2.0: CTB_NearestEventMV Plugin: Click Here to Download
List of Script Calls for convenient reference:
Spoiler
JavaScript:
Script calls:
   $gameMap.nearestEvent()
   $gameMap.nearestEventId()
   $gameMap.eventsByDistance()
   $gameMap.eventIdsByDistance()

To use a notetag filter:
 Place a notetag like <target> into an events notebox
 then use any of the the following script calls:
   $gameMap.nearestEvent('target')
   $gameMap.nearestEventId('target')
   $gameMap.eventsByDistance('target')
   $gameMap.eventIdsByDistance('target')

Here is an example of how to set a self-switch using this:
JavaScript:
$gameSelfSwitches.setValue([$gameMap._mapId, $gameMap.nearestEventId('target'), 'A'], true);
(Tested and does work exactly as it should even for the custom spawned events too 😉)

Perhaps you can do as needed now?
@ct_bolt is the scriptcall used on an event or moveroute for the selfswitches?
and not require customEvents?

if it can be both with and without, I think that scriptcall as sample
can also be in the plugin helpfile how it could be used 😉

you are amazing regardless.
@ct_bolt the updated plugin seems to be working exactly as it should! The only problem now is just how RMMV handles event deletion. Apparently when an event is "deleted" it simply marks it as disabled, however your NearestEvent plugin it still grabbing those disabled event IDs, so I have a bunch of ghost events being targets :uswt:

Not sure what the easiest way to avoid that would be, but I tried checking to see if it was possible to remove note tags on events, and apparently that was a dead end based on how notes are cached when the game loads.

So the only other things I can think of would be either: is it possible to ignore the _erased property if it's set to true, or could the target be based on a Comment on an event page instead of a Note tag? If neither of those are good solutions, I apologize. I'm still trying to learn JS and still have a long way to go lol!

Either way, thank you for all your help! I'm sure I could find a workaround in one way or another if the ghost target events can't be remedied somehow. Thanks again!!
@ct_bolt is the scriptcall used on an event or moveroute for the selfswitches?
and not require customEvents?

if it can be both with and without, I think that scriptcall as sample
can also be in the plugin helpfile how it could be used 😉

you are amazing regardless.
Script call should work anywhere that script can be entered.
Yep it can be used on regular events and also the custom ones created with Hudell's Custom Event Plugin 😉 No need to use Hudell's plugin but the also now the option is now there 🙂

Added the example of setting a self switch script call to the plugin 😉
Thank you for mentioning that 🙂 Good thinking 🙂

@ct_bolt the updated plugin seems to be working exactly as it should! The only problem now is just how RMMV handles event deletion. Apparently when an event is "deleted" it simply marks it as disabled, however your NearestEvent plugin it still grabbing those disabled event IDs, so I have a bunch of ghost events being targets :uswt:

Not sure what the easiest way to avoid that would be, but I tried checking to see if it was possible to remove note tags on events, and apparently that was a dead end based on how notes are cached when the game loads.

So the only other things I can think of would be either: is it possible to ignore the _erased property if it's set to true, or could the target be based on a Comment on an event page instead of a Note tag? If neither of those are good solutions, I apologize. I'm still trying to learn JS and still have a long way to go lol!

Either way, thank you for all your help! I'm sure I could find a workaround in one way or another if the ghost target events can't be remedied somehow. Thanks again!!
Updated to adjust for erased events ☺️
Let me know how it goes, seems to work as needed from my brief testing :popcorn:

v2.01: CTB_NearestEventMV Plugin: Click Here to Download

Might add more to this later like custom conditions and reading notes per page.
@ct_bolt You are a miracle worker! This latest update looks like it has solved all my problems I had been having!

After testing, there's one only one more issue that popped up, and I was worried I'd have to come to you for help, but I wanted to try and find a solution on my own. And I did!

The problem was that sometimes there weren't any targets on the map because their spawn rate was low, and when that was the case, I'd get an error because I was trying to fire a projectile at a target that wasn't there. After wracking my brain I realized I could just put:
JavaScript:
$gameMap.nearestEvent('target') == null
into a conditional branch, so if no targets existed on the map, nothing would happen (I'm sure that would be an obvious simple solution, but as a newbie to JS, it made me pretty happy to figure it out :uhappy: Lol!

Thanks again for your help with this! You've built a bridge over a once uncrossable river for me!
@ct_bolt You are a miracle worker! This latest update looks like it has solved all my problems I had been having!

After testing, there's one only one more issue that popped up, and I was worried I'd have to come to you for help, but I wanted to try and find a solution on my own. And I did!

The problem was that sometimes there weren't any targets on the map because their spawn rate was low, and when that was the case, I'd get an error because I was trying to fire a projectile at a target that wasn't there. After wracking my brain I realized I could just put:
JavaScript:
$gameMap.nearestEvent('target') == null
into a conditional branch, so if no targets existed on the map, nothing would happen (I'm sure that would be an obvious simple solution, but as a newbie to JS, it made me pretty happy to figure it out :uhappy: Lol!

Thanks again for your help with this! You've built a bridge over a once uncrossable river for me!
Yay! Glad to hear it's working as needed.
I went ahead and gave it another update with some really helpful new features too 😉
The major one is probably now you can use comments to set this up per page 😉
Like this:
1662416171019.png

& can also now even be used with javascript to setup conditions in the comment 😉
Like this:
1662416267743.png


& also can check against other events too like this:
JavaScript:
$gameMap.nearestEventId('target', $gameMap.event(1))

Spoiler: Reference/Help Document
JavaScript:
 Script calls:
   $gameMap.nearestEvent()
   $gameMap.nearestEventId()
   $gameMap.eventsByDistance()
   $gameMap.eventIdsByDistance()

 To use a notetag filter:
   Place a notetag like <target> into an event's note field

 To use a comment as a notetag use a comment like the following examples:
  <target: true/>
  <target: $gameVariables.value(30) > 5/>

 Then use any of the the following script calls:
   $gameMap.nearestEvent('target')
   $gameMap.nearestEventId('target')
   $gameMap.eventsByDistance('target')
   $gameMap.eventIdsByDistance('target')

 This can also be used to check against other events like this:
   $gameMap.nearestEventId('target', $gameMap.event(1))
 
Example of how to set a self-switch using this:
   $gameSelfSwitches.setValue([$gameMap._mapId, $gameMap.nearestEventId('target'), 'A'], true);

Well tada! lol

v2.10: CTB_NearestEventMV Plugin: Click Here to Download

I think it's probably pretty complete now ☺️
Super excited for these additional features! Unfortunately, I've run into my first bug with the script :uswt:

It looks like if I still have <target> in the note of the event, it works. But if I am relying only on the comment <target: true/> in an event, when I try to grab the nearest event I get this error:
TypeError Cannot read property 'target' of undefined.

And here's an F8 screen grab if that's helpful at all:
errorMessage.PNG


If you need more information to narrow down what could be causing this, let me know and I can try to include more information :uhappy:
Super excited for these additional features! Unfortunately, I've run into my first bug with the script :uswt:

It looks like if I still have <target> in the note of the event, it works. But if I am relying only on the comment <target: true/> in an event, when I try to grab the nearest event I get this error:
TypeError Cannot read property 'target' of undefined.

And here's an F8 screen grab if that's helpful at all:
View attachment 239779

If you need more information to narrow down what could be causing this, let me know and I can try to include more information :uhappy:
Oh woops lol... never tested it without other ones having it in the notebox.
Fixed now 😉
(for some reason custom events don't get assigned a meta object the the data unless they have something in the notebox... but now I have them do that to prevent such errors)

JavaScript:
$gameMap.nearestEvent('target') == null
Also added a function call to do this if you want instead, but of course that works too. Either way really... just figured I'd add a function call anyway though.
Would be like this:
JavaScript:
$gameMap.hasNearEvent('target')

v2.11: CTB_NearestEventMV Plugin: Click Here to Download

Now I think everything should work perfect ☺️
And now I'm getting these errors:
TypeError Cannot read property 'list' of undefined.
errorMessage2.PNG


I'm so sorry this is being such an issue :usad: And I wish I was better at diagnosing the issue.
And now I'm getting these errors:
TypeError Cannot read property 'list' of undefined.
View attachment 239794


I'm so sorry this is being such an issue :usad: And I wish I was better at diagnosing the issue.
LMAO! Dang.. didn't take into account events that have a pageIndex of -1 (meaning no active page)

Ok fixed. 🙂👍
& hey no worries at all, it's all part of the process. You're doing great at being a tester 😉 🙂

v2.14: CTB_NearestEventMV Plugin: Click Here to Download

Now for real I think everything really should work perfectly for real this time lol ☺️
Give 'er a whirl, should be good to go now :popcorn:
Hi. A plugin may be a better solution, but in case you're still having issues with it, I can suggest a workaround that I'm using for my own game.
@ct_bolt I'm very late to this, (and rather new) but once I get the ID of the nearest event, how would I then access that ID to make another event move toward it?

Currently, I've been using Yanfly's Move Route Core. The script call is "CRASH MOVE TO: EVENT X". This worked great for manually putting in a specific event ID, but I need it to automatically find the ID of the nearest event and then move toward that.

Would it be possible to plug the nearest event id into that "X" part? And if so, how? Any help would be GREATLY appreciated!

Thank you so much, this plugin looks awesome!

Original thread: https://forums.rpgmakerweb.com/threads/event-id-of-nearest-event-to-player-rmmv.151061/