NPC Patrol Script

Hi.. I have a 48x20 world map, and I want an NPC (event) to do patrol from the most left of the map to the most right of the map, back and forth.
So, I did the following
1. Add an event (on location x: 1, y:12)
2. Set image (soldier sprite)
3. Autonomous Movement -> Type: Custom -> Route... -> Script below
Code:
this.moveStraight(this.findDirectionTo(48, 12));
if (this.pos(48, 12)) { this._moveRoute.repeat = false; };
4. Options -> Repeat Movements : Checked
And the event did it, but only move it one way.
So, how to do moving back and forth?
i never use custom route script before... but maybe try this:
for example my event start at (9,4) then want to patrol to (14,4)
you need 4 custom move route -> Script
first
Code:
if(!this._returning) this.moveStraight(this.findDirectionTo(14, 4));
second
Code:
if(this._returning) this.moveStraight(this.findDirectionTo(9, 4));
third
Code:
if (this.pos(14, 4)) { this._returning = true};
fourth
Code:
if (this.pos(9, 4)) {this._returning = false};
don't forget to set repeat movement to ON.
and maybe skip if cannot move also ON.

in case you want to understand the logic... the move route above will execute like this.
Spoiler
at the begining this._returning will not exist thus equal to null and if checked in if statement will return false... thus the move route will execute the first move route (going to 14,4).

when the event reach (14,4)... the third move route will execute that set this._returning = true.
after that the first move route will not execute because of that and the second move route will execute instead and moving the event to (9,4)

when the event finally back at (9,4)... the fourth move route will execute and set this._returning = false. and after that the second move route will not execute and first one will run again instead.

now you only need to change (9,4) and (14,4) to coordinate of your project.
hope this help.
It works exactly what I need sir.. thanks so much.. you're the best sir!

Original thread: https://forums.rpgmakerweb.com/threads/npc-patrol-script.128371/