Question about a small script code.

Hi all,

Im having a problem with a small script code.

I want an event to change self switch A to true, when the player is nearby.

So I wrote:
var px = $gamePlayer.x;
var py = $gamePlayer.y;
var ex = $gameMap.event(32).x;
var ey = $gameMap.event(32).y;
if(px <= (ex+5) && px >= (ex-5) && py <= (ey+5) && py >= (ey-5)) {$gameSelfSwitches.setValue([1,32,'A'], true};

But is just doesnt seem to work, maybe somebody knows whats up.
Thnk you,
Deabt
An easier way to find the distance between two points (events in this case) is to use this formula:

Code:
var dist = Math.sqrt((ex - px) ** 2 + (ey - py) ** 2);
if (dist < 5) $gameSelfSwitches.setValue("1,32,A", true);
else $gameSelfSwitches.setValue("1,32,A", false);

Edit: Or shortened, in case you're using the script box in an event and need to save space:

Code:
$gameSelfSwitches.setValue("1,32,A", Math.sqrt((ex - px) ** 2 + (ey - py) ** 2) < 5);
Thank you very much, this works way better
you also are able to use
$gameMap.event(this.eventId()

as it's current event that activate it., as for the selfswitch setvalue,
32 must be included unless this is called from another event,
else you can use this as well:

$gameSelfSwitches.setValue([$gameMap.mapId(), this.eventId(), 'A'], true);

if its inside the same event 🙂
Code:
$gameSelfSwitches.setValue("1,32,A", Math.sqrt((ex - px) ** 2 + (ey - py) ** 2) < 5);

That's beautiful~ Ain't that Pythagoras? Does it check an actual radius?

I used to using Math.abs(ex - px) + Math.abs(ey - py) to find distance, but that's more like the number of step.
That's beautiful~ Ain't that Pythagoras? Does it check an actual radius?
It's the Euclidean metric*, which is basically the same as Pythagoras.

Side note: a better way to use the Euclidean metric is:

Code:
var dist = (ex - px) ** 2 + (ey - py) ** 2;
if (dist < 5 * 5) $gameSelfSwitches.setValue("1,32,A", true);
else $gameSelfSwitches.setValue("1,32,A", false);

This is because square root is an expensive operation. If you're not doing it frequently it's likely fine the other way, mind you. This version would be better for a parallel event, for example.

I used to using Math.abs(ex - px) + Math.abs(ey - py) to find distance, but that's more like the number of step.
That's the taxicab metric*, which is a perfectly reasonable thing to use for distance in a tile-based game.

* "metric" is just a fancy mathematical way of saying "a way of measuring distance".
This is excellent, thank you all for your help!

Original thread: https://forums.rpgmakerweb.com/threads/question-about-a-small-script-code.124162/