Need some help with Javascript

I'm using a certain line of code to make enemies move to a specific point on the map. It works fine with just one, but problems arise once I add a second enemy. Once one enemy reaches its specific map point, the other stops. I don't know much about Javascript, so I can't be 100% certain as to why this is happening. However, my guess is that since both lines of code are basically the same, it's using the same variable in some place. (Might not make much sense, but again, my Javascript knowledge is limited.

Below is the line of code I'm using for one of the enemies. (The other is the exact same except for the cords). I'm hoping someone could help me understand this code and how to make it work.

JavaScript:
var d = this.findDirectionTo(9, 9); if (!d || !this.canPass(this.x, this.y, d)) { this.forceMoveRoute({ list: [{ code: 0 }] }); this.setMovementSuccess(true); this._moveRouteIndex--; } else this.moveStraight(d);
Okay, that barely qualifies as "a line of code". Here it is properly laid out:

JavaScript:
var d = this.findDirectionTo(9, 9);
if(!d || !this.canPass(this.x, this.y, d)) {
    this.forceMoveRoute({ list: [{ code: 0 }] });
    this.setMovementSuccess(true);
    this._moveRouteIndex--;
} else this.moveStraight(d);

Your guess is wrong – there's no common variable being used there that would interfere across two different events.

So, let's see. What it does is:

  • Run the A* pathfinder to determine the next hop on the best path to (9,9).
  • If there is a route to that path, and the direction is passable, move in that direction (the "else" branch). But, in fact, the canPass call is redundant, as findDirectionTo is already checking passability. So you could simplify it to just if(!d)
  • If there is no route to that path (findDirection returned 0), you're doing something weird:
    • The forceMoveRoute call is equivalent to a Set Movement Route command with all 3 checkboxes unticked and no move commands. In other words: setting a blank movement route that does not loop, does not skip if it can't move, and does not wait for completion.
    • Then you're making the move route consider the current move to be a success. That doesn't really make sense, since you just overrode your move route with a new one.
    • Finally, you're decrementing the move route index… but it's already 0, so now you're making it negative?

Keeping all that in mind, I think your code can be simplified to just this:

JavaScript:
var d = this.findDirectionTo(9, 9);
if(d) this.moveStraight(d);

Though I could be missing something.

That might fix the issue already, as you mentioned that the problem occurred when one enemy reached its destination. In other words, it occurred when findDirectionTo returned 0 because the enemy was already on the target location, which thus triggered it to do that weird move route override thing. Since the simplified code doesn't do that, it might be enough to fix your issue. But, since it doesn't do that, it might end up creating a different issue instead.

Let me know how it goes.
Okay, that barely qualifies as "a line of code". Here it is properly laid out:

JavaScript:
var d = this.findDirectionTo(9, 9);
if(!d || !this.canPass(this.x, this.y, d)) {
    this.forceMoveRoute({ list: [{ code: 0 }] });
    this.setMovementSuccess(true);
    this._moveRouteIndex--;
} else this.moveStraight(d);

Your guess is wrong – there's no common variable being used there that would interfere across two different events.

So, let's see. What it does is:

  • Run the A* pathfinder to determine the next hop on the best path to (9,9).
  • If there is a route to that path, and the direction is passable, move in that direction (the "else" branch). But, in fact, the canPass call is redundant, as findDirectionTo is already checking passability. So you could simplify it to just if(!d)
  • If there is no route to that path (findDirectionreturned 0), you're doing something weird:
    • The forceMoveRoute call is equivalent to a Set Movement Route command with all 3 checkboxes unticked and no move commands. In other words: setting a blank movement route that does not loop, does not skip if it can't move, and does not wait for completion.
    • Then you're making the move route consider the current move to be a success. That doesn't really make sense, since you just overrode your move route with a new one.
    • Finally, you're decrementing the move route index… but it's already 0, so now you're making it negative?

Keeping all that in mind, I think your code can be simplified to just this:

JavaScript:
var d = this.findDirectionTo(9, 9);
if(d) this.moveStraight(d);

Though I could be missing something.

That might fix the issue already, as you mentioned that the problem occurred when one enemy reached its destination. In other words, it occurred when findDirectionTo returned 0 because the enemy was already on the target location, which thus triggered it to do that weird move route override thing. Since the simplified code doesn't do that, it might be enough to fix your issue. But, since it doesn't do that, it might end up creating a different issue instead.

Let me know how it goes.
Thank you for the help! It did solve the initial problem of the enemies not returning properly. However, a few more problems have arisen instead. Mainly, once returning to the specified point, they are no longer able to move at all. Though this is only when both repeat movements and wait until completion are turned on in the movement route. If only one of them is turned on, they don't return to the specified point, but are still able to move.

The original line of code I used was copied and modified from a massive list of script calls. (OG script below). It says that the route will stop once the target tile is reached, and this did in fact happen with the OG script. Though it's not with the new script you gave me. Would you know how to make the new script end once the target tile has been reached?
Code:
"// Path to (2, 6) using the built-in pathfinding
var x = 2, y = 6; var d = this.findDirectionTo(x, y); if (!d ||
!this.canPass(this.x, this.y, d)) { this.forceMoveRoute({ list: [{ code: 0
}] }); this.setMovementSuccess(true); this._moveRouteIndex--; }
else this.moveStraight(d);"
Well, the part I removed was presumably intended to make it stop once it reached the target tile. It's a strange way to do it, though. If it works, it probably only works in Set Movement Route, not in a route set in the left panel of the event. Set Movement Route sets a forced movement route for the event; this code seems to replace the forced movement route with a blank one, which will expire immediately. But once it expires, it'll go back to whatever its regular movement route is; so it'll probably have no effect if used in an event's default movement route.

So… were you using that code in Set Movement Route? Or, did you put it in the event's default movement route?

If you need something that works in the event's default movement route, I think the best option would be to set a self switch that activates a different page. If that's not an option, you could rewrite the movement route settings. This is something that might be reset when the map is reloaded, though. At minimum, that happens when you leave the map and re-enter, but some things of this nature also reset by simply opening and closing the menu. I'm not sure if this would.

Self switch method (replace A with a different self switch if needed):
JavaScript:
var d = this.findDirectionTo(9, 9);
if(!d) {
    $gameSelfSwitches.setValue([$gameMap.mapId(), this.eventId(), 'A'], true);
    this.setMovementSuccess(true);
} else this.moveStraight(d);

Rewriting movement route settings method:
JavaScript:
var d = this.findDirectionTo(9, 9);
if(!d) {
    this._moveRoute.repeat = false;
    this.setMovementSuccess(true);
} else this.moveStraight(d);

If you were using a Set Movement Route all along, then I probably need more information. For example, if one enemy's destination being occupied happens to block the other enemy's only route to its own destination, then the second enemy would certainly stop once the first enemy reaches its destination.
Yes, I was using it in the Set Movement Route. The code you gave me works in it though, but on once.

The enemies in question are meant to chase the player, and after a certain amount of time, return to their original position. Then go back to their default movement route (which IS in the event's default movement route). The chase itself is triggered by a plug in, but as far as I know, that shouldn't interfere with this. Below I'll post pictures of the pages for the event so you can better understand what I'm trying to do.

Thank you once again for your help so far.
Page 1.png
Page 2.png
Page 3.png
Default ghost movement route.png
@Touya - just to check...I notice you're using switch ID 24 in that event. Are you using the same switch in the other event?


@Solar_Flare
Spoiler: some notes on the original script call
  • If there is a route to that path, and the direction is passable, move in that direction (the "else" branch). But, in fact, the canPass call is redundant, as findDirectionTo is already checking passability.
findDirectionTo should check passability, yea. I wrote that example a while ago...I don't remember why I added the canPass stuff as well, maybe just paranoia. 😴

Then you're making the move route consider the current move to be a success.
This is related to the move route index (advanceMoveRouteIndex). In MV there is still a bug where the index skips a step after being restored. This has been fixed in MZ by marking processRouteEnd as an unsuccessful move command if the route is neither autonomous nor repeating. For repeating routes, index is instead reset to -1 on route end (and then gets incremented to 0 right afterwards), hence the index decrement.

To work the same in all versions of MV/Z the movement should be marked successful and the index manually decremented to compensate. Thus the current "Path to Tile" script call in the spreadsheet (currently row 757).

Rewriting movement route settings method:
JavaScript:
var d = this.findDirectionTo(9, 9);
if(!d) {
this._moveRoute.repeat = false;
Just for info: this approach would mutate the move route object (a sub-property of the event's $dataMap record), which is generally a bad idea. That's why the Script Call List example sets a blank move route instead.
Just for info: this approach would mutate the move route object (a sub-property of the event's $dataMap record), which is generally a bad idea. That's why the Script Call List example sets a blank move route instead.
Oh, you're right. I forgot that _moveRoute would just be a direct reference to something under $dataMap. If taking that approach, you'd want to make a copy and set repeat to false on the copy. Something like:
JavaScript:
this._moveRoute = {list: this._moveRoute.list, repeat: false};

Maybe copy over the other two booleans if you need those.
@Touya - just to check...I notice you're using switch ID 24 in that event. Are you using the same switch in the other event?


@Solar_Flare
Spoiler: some notes on the original script call
findDirectionTo should check passability, yea. I wrote that example a while ago...I don't remember why I added the canPass stuff as well, maybe just paranoia. 😴


This is related to the move route index (advanceMoveRouteIndex). In MV there is still a bug where the index skips a step after being restored. This has been fixed in MZ by marking processRouteEnd as an unsuccessful move command if the route is neither autonomous nor repeating. For repeating routes, index is instead reset to -1 on route end (and then gets incremented to 0 right afterwards), hence the index decrement.

To work the same in all versions of MV/Z the movement should be marked successful and the index manually decremented to compensate. Thus the current "Path to Tile" script call in the spreadsheet (currently row 757).


Just for info: this approach would mutate the move route object (a sub-property of the event's $dataMap record), which is generally a bad idea. That's why the Script Call List example sets a blank move route instead.
Yes, I am using the same switch for both enemies. I figured it would work since once one enemy spots the player, they would all start chasing them. I understand how that would cause problems, but I didn't mention it as it wasn't what I was initially asking about.

I also looked over the code you were talking about and maybe I'm just dumb. But were you recommending a fix for the Set Movement Route command, or the event's movement route? Cause as you can see, I am mainly using set movement route. The event's movement route is the default it's supposed to revert back to after pathfinding the it's point of origin. I tried some of the code and maybe I just put it in wrong, but it didn't work at all.
I just noticed...the last page looks like some kind of WIP (spyglass item?). Just to mention it: I don't see any need to turn off the "Glass" switch at the top of page 2, because if that switch is on then page 2 cannot be active. It doesn't seem relevant to the problem, though, so I'll ignore it for the rest of this post~

I also looked over the code you were talking about and maybe I'm just dumb. But were you recommending a fix for the Set Movement Route command, or the event's movement route?
The stuff in the spoiler was just some technical clarifications about how the Script Call List example was designed. You are using that example how it is intended to be used. I think the problem is with your switches/variable...

Yes, I am using the same switch for both enemies.
OK, let's have a closer look at your event:
  • You're using a plugin to turn on/off a switch named "Sight test", right?
  • When sight is established, the "Chase test" switch is turned on.
  • The "Timer" variable gets +1 every frame the enemy is chasing but can't see the player.
  • When "Timer" is exactly 300, the enemy starts walking home.
  • Once they're home, the "Chase test" switch is turned off.
Seems sensible! Now, a thought experiment: what if there are other enemies sharing those values?
  • "Sight test" switch:
    • OK if the switch is toggled per-event, immediately before running event commands. (I think this is likely.)
    • Conflicts if the switch is toggled at a different time.
    • To check the timing we'd need to know which plugin it is (you can link to the plugin's page/thread).
  • "Chase test" switch:
    • All enemies start and stop chasing at the same time.
    • I.e. when any enemy gets back home, all enemies resume their original, non-chasing behaviour.
  • "Timer" variable:
    • Advances faster with more enemies, since each enemy event gives +1 to the timer.
    • May exceed 300, breaking the "= 300" check:
      • Enemy #1 will start going home;
      • The others will keep chasing until that guy is home;
      • Once enemy #1 is home, all enemies will reset at the same time.
I guess you can see the problem now! 😅

I'm not sure what the best solution might be, with the plugin you're using. To track "going home" separately for each enemy, I'd consider using a range of switches (or just e.g. self-switch A on each enemy). E.g. turn on each enemy's "go home" switch, then turn off the "chase" switch. Each enemy could then have pages like:
  1. Original behaviour (no conditions):
    • (Does whatever that enemy does.)
  2. Going home (condition = self-switch A is ON):
    • Set Movement Route: {Script: etc} (Wait, Repeat)
    • Turn off self-switch A.
  3. Chasing (condition = switch Chase is ON):
    • (Chase stuff.)
Note that if you want to use self-switches for this then you'll need a script call (to toggle a different event's self-switch), e.g.
JavaScript:
// Turn on self-switch A for event ID 2 on this map.
$gameSelfSwitches.setValue([this._mapId, 2, "A"], true);

You could also consider moving the timer/"end chase" control to a new Parallel event to avoid counting multiple times per frame. Again, the actual implementation would depend on what the plugin you're using offers for sight checks. If necessary you could add another switch, e.g.
  • Each enemy event:
    • If (this enemy can see the player):
      • Turn on switch "Player Spotted".
  • Timer event:
    • If switch "Player Spotted" is ON:
      • Timer = 0
      Else:
      • Timer += 1
      • If Timer = 300: (end chase)
    • Turn off switch "Player Spotted".
Hopefully that helps~ 👋
Thanks! I'll have to try this out when I'm free tomorrow and get back to you
I just noticed...the last page looks like some kind of WIP (spyglass item?). Just to mention it: I don't see any need to turn off the "Glass" switch at the top of page 2, because if that switch is on then page 2 cannot be active. It doesn't seem relevant to the problem, though, so I'll ignore it for the rest of this post~


The stuff in the spoiler was just some technical clarifications about how the Script Call List example was designed. You are using that example how it is intended to be used. I think the problem is with your switches/variable...


OK, let's have a closer look at your event:
  • You're using a plugin to turn on/off a switch named "Sight test", right?
  • When sight is established, the "Chase test" switch is turned on.
  • The "Timer" variable gets +1 every frame the enemy is chasing but can't see the player.
  • When "Timer" is exactly 300, the enemy starts walking home.
  • Once they're home, the "Chase test" switch is turned off.
Seems sensible! Now, a thought experiment: what if there are other enemies sharing those values?
  • "Sight test" switch:
    • OK if the switch is toggled per-event, immediately before running event commands. (I think this is likely.)
    • Conflicts if the switch is toggled at a different time.
    • To check the timing we'd need to know which plugin it is (you can link to the plugin's page/thread).
  • "Chase test" switch:
    • All enemies start and stop chasing at the same time.
    • I.e. when any enemy gets back home, all enemies resume their original, non-chasing behaviour.
  • "Timer" variable:
    • Advances faster with more enemies, since each enemy event gives +1 to the timer.
    • May exceed 300, breaking the "= 300" check:
      • Enemy #1 will start going home;
      • The others will keep chasing until that guy is home;
      • Once enemy #1 is home, all enemies will reset at the same time.
I guess you can see the problem now! 😅

I'm not sure what the best solution might be, with the plugin you're using. To track "going home" separately for each enemy, I'd consider using a range of switches (or just e.g. self-switch A on each enemy). E.g. turn on each enemy's "go home" switch, then turn off the "chase" switch. Each enemy could then have pages like:
  1. Original behaviour (no conditions):
    • (Does whatever that enemy does.)
  2. Going home (condition = self-switch A is ON):
    • Set Movement Route: {Script: etc} (Wait, Repeat)
    • Turn off self-switch A.
  3. Chasing (condition = switch Chase is ON):
    • (Chase stuff.)
Note that if you want to use self-switches for this then you'll need a script call (to toggle a different event's self-switch), e.g.
JavaScript:
// Turn on self-switch A for event ID 2 on this map.
$gameSelfSwitches.setValue([this._mapId, 2, "A"], true);

You could also consider moving the timer/"end chase" control to a new Parallel event to avoid counting multiple times per frame. Again, the actual implementation would depend on what the plugin you're using offers for sight checks. If necessary you could add another switch, e.g.
  • Each enemy event:
    • If (this enemy can see the player):
      • Turn on switch "Player Spotted".
  • Timer event:
    • If switch "Player Spotted" is ON:
      • Timer = 0
      Else:
      • Timer += 1
      • If Timer = 300: (end chase)
    • Turn off switch "Player Spotted".
Hopefully that helps~ 👋
Just tried it out! Things seem to be working with just one enemy (Testing out just one to make sure the code actually works). However, the movement script only works once. If the enemy tries to navigate back to its point of origin a second time, it's as if the move route doesn't run
Edit: Here's the link to the plug in I'm using for line of sight https://quxios.github.io/plugins/QSight
Not sure how this works exactly, but this thread can be closed. I've decided to give up on not only this project, but game creation as well. I no longer need this answered or anything so the thread can be closed
OK, I'm back!

Oh, huh. All right then, I'll close it for you.

This thread is being closed, per OP's request. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

Just click the "⚠Report" button at the bottom of this post if you change your mind~

For reference, the next thing I'd've asked for would be:
  • New screenshots of your event pages, and
  • Screenshot(s) of your Plugin Manager showing all plugins you're using and their load order.
It's possible that there's a mistake/oversight in my suggestions, your implementation, or both...or that you're simply using conflicting plugins. E.g. a plugin for pixel- and/or 8-directional-movement might not work as anticipated with 4-directional tile-based pathfinding.

Original thread: https://forums.rpgmakerweb.com/threads/need-some-help-with-javascript.182523/