Have Event Move to Nearest Event With a Specific Notetag

Hello! I'm rather new to this and still learning javascript, but here goes:

I'm using RPGMAKER MV and I need an event to check for the nearest berry bush event and walk to it. This isn't part of a cutscene, just a parallel process once a "Harvest" switch is turned on.

Right now, I'm using Yanfly's Move Route Core. The script call: "CRASH MOVE TO: EVENT X" has worked great for manually putting in a specific berry bush. But since the berry bushes are spawned into the map at random spots, I need the event to be able to find the nearest one and move toward it on its own.

I've also been using CBT_NearestEventMV. It looks like the script call I would need is:

$gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId))

But I'm not sure how to put these two together. I can use the script call but then I don't know how to access the Id that it grabbed and put it into the "CRASH MOVE TO:" type command. Is it even possible to combine the two? Or would I need to use some extra js code in addition to CBT's script call.

Thank you in advance!
Hello! I'm rather new to this and still learning javascript, but here goes:

I'm using RPGMAKER MV and I need an event to check for the nearest berry bush event and walk to it. This isn't part of a cutscene, just a parallel process once a "Harvest" switch is turned on.

Right now, I'm using Yanfly's Move Route Core. The script call: "CRASH MOVE TO: EVENT X" has worked great for manually putting in a specific berry bush. But since the berry bushes are spawned into the map at random spots, I need the event to be able to find the nearest one and move toward it on its own.

I've also been using CBT_NearestEventMV. It looks like the script call I would need is:

$gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId))

But I'm not sure how to put these two together. I can use the script call but then I don't know how to access the Id that it grabbed and put it into the "CRASH MOVE TO:" type command. Is it even possible to combine the two? Or would I need to use some extra js code in addition to CBT's script call.

Thank you in advance!

I don't know if you can run arbitrary code within the movement route command, but the Yanfly page also has script calls for the various functionalities if you scroll down the page, so you should be able to use that; so you could try something like

this.moveToEvent($gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId)), true)

in a Script command? I haven't tested it myself, though.
Wow, @Showsni thanks for the quick response! I got rid of the movement route command and copy/pasted the code into a script command instead. Nothing yet, sadly... Which is strange because it totally looks like it should work.

Is this what you meant?

Screenshot (6).png


I double checked that the right note tag was on the berry bush event. But the little character who is supposed to do the walking still doesn't move with the new script.

Screenshot (7).png



It's possible I already messed up CBT's script call from the start, as the original was:

$gameMap.nearestEventId('target', $gameMap.event(1))

Instead of using "$gameMap.event(1)", I tried to plugin "this._eventId", as the characters doing the harvesting will also be spawned in, making event ids a bit tricky.


But I'll keep playing with it and looking at Yanfly's plugin to see what I can sort out, but any additional insight would be SUPER helpful! I've been stuck on this for a couple weeks now.
Have you tried a conditionnal script?

Something like :


JavaScript:
// Find the nearest berry bush event
var nearestBushId = $gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId));

// If a nearest berry bush is found, move towards it
if (nearestBushId > 0) {
  this.moveToEvent(nearestBushId, true);
}


This would ensure that wherever the nearest active bush may be, it would go towards that one.

You seem to have a parrallel process that checks whether Harvest is on or off,
So for the event that needs to move, you could try and run the script I mentioned, so that whenever Harvest is set to on, it will check the nearest active berry bush.


Edit : My bad, the script shouldn't run in the parrallel process, but for each event that needs to be moved, just check if the condition for the movement is met as you did in your screenshots.
I double checked that the right note tag was on the berry bush event. But the little character who is supposed to do the walking still doesn't move with the new script.
i think the issue here is that "this" in a script box refers to the interpreter, not the event
try
Code:
$gameMap.event(this.eventId()).moveToEvent($gameMap.nearestEventId('berrybush', $gameMap.event($gameMap.event(this.eventId()).eventId())))
Thank you all so much! :LZSproud: I've plugged each of these solutions in and haven't had any luck yet, but I'm going to revisit this after I've had some shut eye. I'm sure I'm slipping up somewhere.
UPDATE: (Wanted to try one more thing, I couldn't help myself.)

I opened up a blank project and tried again. With the conditional branch script, I got an error message saying var nearestBushId was not a function. :LZSskeptic:

With the string of code from @Robro33 it worked at least until I introduced Yanfly's Event Spawner, which is what I had been using before. When I spawned things in from another map, it didn't like it and the character froze up again.

This is probably a silly question, but would "$gameMap" have anything to do with it, since I'm pulling events in from another map? I may have to resort to some workarounds...
UPDATE: (Wanted to try one more thing, I couldn't help myself.)

I opened up a blank project and tried again. With the conditional branch script, I got an error message saying var nearestBushId was not a function. :LZSskeptic:

With the string of code from @Robro33 it worked at least until I introduced Yanfly's Event Spawner, which is what I had been using before. When I spawned things in from another map, it didn't like it and the character froze up again.

This is probably a silly question, but would "$gameMap" have anything to do with it, since I'm pulling events in from another map? I may have to resort to some workarounds...

var nearestBushId is indeed not a function, in the code I sent it's a variable gathering data from $gameMap.nearestEventId()

You said you ran from a blank project, did you include the CBT_NearestEventMV? as nearestEventID is related to this plugin.


If the issue is the character freezing when it spawns from another map, you could try and use
JavaScript:
$gameMap.requestRefresh();
in your event that should be moving.

This would ensure to process it dynamically as it would add the event to current $gameMap array.

You have to make sure the event that should be moving is continuously checking if Harvest is ON, so you'd have to make it run in parrallel mode.


Additionnaly, you could try and press F8 to open up the console and check for errors if it still doesn't work.

The script call in the event that should be moving should be :

JavaScript:
$gameMap.requestRefresh();
var nearestBushId = $gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId));
if (nearestBushId > 0) {  this.moveToEvent(nearestBushId, true);}

Else, you could try and make sure the script is interpreted as an event function like this :
JavaScript:
$gameMap.requestRefresh();
(function() {
    // Check if the "Harvest" switch is ON
    if ($gameSwitches.value(SWITCH_ID)) {  // Replace SWITCH_ID with the actual switch ID for "Harvest"
        // Find the nearest berry bush event
        var nearestBushId = $gameMap.nearestEventId('berrybush', $gameMap.event(this.eventId()));
        
        // If a nearest berry bush is found, move towards it
        if (nearestBushId > 0) {
            this.moveToEvent(nearestBushId, true);
        }
    }
})();
i think the issue here is that "this" in a script box refers to the interpreter, not the event

This could be the case actually, so the approach would be to make sure you are accessing "this" withing the interpreter.

Try something like this maybe :


JavaScript:
$gameMap.requestRefresh();

(function() {
    if ($gameSwitches.value(SWITCH_ID)) {  // Replace SWITCH_ID with the actual switch ID for "Harvest"
        var nearestBushId = $gameMap.nearestEventId('berrybush', $gameMap.event(this._eventId));
        if (nearestBushId > 0) {
            $gameMap.event(this._eventId).moveToEvent(nearestBushId, true);
        }
    }
}).call(this);

"this._eventId" instead of "this.eventId" would ensure you are getting acces from the interpreter's private property that is "_eventId"
wrapping it in ".call(this)" allows it to use "this" refering the interpreter instead of the event.
With the string of code from @Robro33 it worked at least until I introduced Yanfly's Event Spawner, which is what I had been using before. When I spawned things in from another map, it didn't like it and the character froze up again.
just tried it myself. it appears that spawned events do not contain all the data regular ones do. the most important here one being the notebox.

Possible solutions would be patching the event spawner plugin to include the meta data into spawned events, or patching the CTBolt plugin to include a function that takes a spawned event and uses it to look up the source event's data for the notetag.
i wont have the time to look further later, but ill try the first when i get the time. it doesnt sound like there would be any difficulties in doing it, but its weird that it already isnt included to begin with
just tried it myself. it appears that spawned events do not contain all the data regular ones do. the most important here one being the notebox.

Possible solutions would be patching the event spawner plugin to include the meta data into spawned events, or patching the CTBolt plugin to include a function that takes a spawned event and use it to look up the source event's data for the notetag.
i wont have the time to look further later, but ill try the first when i get the time. it doesnt sound like there would be any difficulties in doing it, but its weird that it already isnt included to begin with

There is a way to manually enter the event's notetag in a script call.


JavaScript:
//Use yanfly event spawner
$gameMap.spawnEvent(x, y, eventId, templateMapId);

//Set Notetag manually
var spawnedEvent = $gameMap.event(eventId); //replace eventId with real Id
spawnedEvent.note = '<berrybush>'; //Give it a notetag

//---
//If it still does not retain the notetag, you could try the meta property
spawnedEvent.event().meta['berrybush'] = true;
There is a way to manually enter the event's notetag in a script call.
true. i got caught up on thinking that it would be easier in the long run having the function that spawns the events to also add the notetag in at creation instead of finding the event afterwards and adding it in then, but that depends on how often this is being done in different places. your way is probably the way to go if its just a few times
true. i got caught up on thinking that it would be easier in the long run having the function that spawns the events to also add the notetag in at creation instead of finding the event afterwards and adding it in then, but that depends on how often this is being done in different places. your way is probably the way to go if its just a few times
It would take a bit more work to try to grab the meta data from the data map (I didn't really check thoroughly so I am sure there is a way) and since you are using a script call already, maybe something like what you are suggesting will be more efficient?

For OP: Since you are dealing with spawned events only it seems, you can filter it with $gameMap._spawnedEvents. If you are looking to look for a specific event throughout the map, whether spawned or not, $gameMap.events() will show it and you can weed through it from there.

Edit: Found it, here is what you need to use instead (updated):
JavaScript:
Game_Map.prototype.spawnEvent = function(mapId, eventId, x, y, preserved) {
  DataManager.extractMetadata(Yanfly.PreloadedMaps[mapId].events[eventId]);
  var spawnId = this._spawnedEvents.length + Yanfly.Param.EventSpawnerID;
  $gameTemp._SpawnData = {
    baseMapId: this.mapId(),
    spawnId: spawnId,
    mapId: mapId,
    eventId: eventId,
    x: x,
    y: y,
    preserved: preserved
  };
  var spawnedEvent = new Game_Event(mapId, eventId);
  this._events[spawnId] = spawnedEvent;
  this._spawnedEvents[spawnId - Yanfly.Param.EventSpawnerID] = spawnedEvent;
  $gameTemp._SpawnData = undefined;
};
Extracting the meta data will make it available for you and you won't need to use other tactics to try to find it. Here are the results from using the console log:

s1.png



This way you don't have to do it every time you use the spawn script, and it is loaded from what is already there in the event. With this, you have access to other meta tags as well as needed. You should still be able to filter/search for the specific event.

As for CTB's plugin, it should work as intended now with this change.
Wow!! Thank you all so much, I was not expecting to get this much help! I'll catch up on all this as soon as I can and try it.
There is a way to manually enter the event's notetag in a script call.


JavaScript:
//Use yanfly event spawner
$gameMap.spawnEvent(x, y, eventId, templateMapId);

//Set Notetag manually
var spawnedEvent = $gameMap.event(eventId); //replace eventId with real Id
spawnedEvent.note = '<berrybush>'; //Give it a notetag

//---
//If it still does not retain the notetag, you could try the meta property
spawnedEvent.event().meta['berrybush'] = true;
Alright, so it looks like I'm newer to javascript than I thought. But before I dive in too deep with something like the epic solution from @bass2yang , I just want to make sure I'm not messing up something really stupid, such as where I'm putting these script calls.

@Artille Is this what it should look like? These screenshots are from my "blank" project where I do have all the plugins. Apologies for the misunderstanding earlier.

This is the event that supposed to harvest the berries:
Screenshot (9).png


And this is the event I have running on the map where I need the events spawned. The first spawn is the berry bush, the second is the character. I couldn't get the first note tag solution to work, so I'm trying the meta one.

Screenshot (10).png

Thanks again!

The first screenshot looks as I think it should.
It runs in parrallel, so it should check at any time if there is a berrybush, and if there is, the character should move towards it.

As a breakdown, does that part work without the spawning?
Like, if you have the character on the same map as the berrybush when it spawns, does it do the job?


The second screenshot has me puzzled, I'm pretty sure it runs only once spawning the bush in the region, then giving it's notetag, then spawning the character.
But unless you have something to control it's self switch A back to Off, this event will only run once at all.

Even so, if this is as a test, you aren't setting the meta correctly.
RPG Maker runs each script branch individually, so you are asking to set a meta property to something it may consider null or out of reach.
The full script (for the notetag setting) should be something like this :
JavaScript:
// Spawn Berry Bush Event in Region
Yanfly.SpawnEventInRegion(2, 2, 20, true);
Yanfly.SpawnEventAt(2, 1, 4, 5, true);

// Refresh the map to ensure events are added
$gameMap.requestRefresh();

// Set meta property for the spawned berry bush
var spawnedEvent = $gameMap.event(eventId); //replace eventId with real Id of the berry bush
if (spawnedEvent) {
spawnedEvent.event().meta = spawnedEvent.event().meta || {};
spawnedEvent.event().meta['berrybush'] = true; //Give it a notetag
}

This ensures it knows what event you are trying to edit the meta properties from.
To answer your question, yes. It works quite well if the two events start out on the map! So it's just the spawning bit that's messing everything up. Beginning to wonder if I might have to find a different workaround to have multiples of the same events placed at random...

In any case, the reason for the self switch was because otherwise it keeps spawning infinite of that event into that region, as seen here:

Screenshot (12).png

If the fairy was moving, I suspect there'd be a whole bunch of her walking around too. But that's a problem I'm willing to tackle on my own later. For now, is the new code I put in. I still can't seem to get the event to move if it is spawned in... I just wanted to put this here to make sure I had everything correct. Thank you so much for your help so far! I hope I'm not taking up too much of your time!

Screenshot (11).png
Doesn't the event spawner maintain the event's name from its template?

Then I'd say just trash all the stuff about trying to create new metadata on spawned events. (not because the idea or code is trash, but because it's clearly not working for you)

Edit the CTB plugin on line 156 to say eventsByName instead of eventsByTag

Then you make berrybush be the name and it should all go painlessly from there.
Doesn't the event spawner maintain the event's name from its template?

Then I'd say just trash all the stuff about trying to create new metadata on spawned events. (not because the idea or code is trash, but because it's clearly not working for you)

Edit the CTB plugin on line 156 to say eventsByName instead of eventsByTag

Then you make berrybush be the name and it should all go painlessly from there
I like the sound of that! On line 156, eventsByTag is immediately followed by (filterTag). Does that need edited as well?

Thank you!
Edit what I said.

Original thread: https://forums.rpgmakerweb.com/threads/have-event-move-to-nearest-event-with-a-specific-notetag.169595/