MV (Solved) Can I make this script call check more than one tile?

Background (skip to next bolded text for meat of the question):

I'm trying to add a feature to my ABS based on clicking the enemy (or ally NPC) event you want to target (for potentially a plethora of uses, but mostly for targeting of various ranged, non-projectile spell effects). I can't use a plugin that allows event activation via click, because the feature needs to still be able to work if the event's active page is a parallel/looping one (core to several other aspects of the ABS). So I've been using a parallel common event to check if there are any events on the clicked tile (yes, after converting screen coords to map tile coords), using a variation of this script call:

Code:
$gameMap.eventIdXy(x, y)

(The variation I'm using is actually $gameMap.eventIdXy_special, from the code @MushroomCake28 provided in this thread - with that code in my game as a plugin, as recommended - so I can receive the IDs of all events on the clicked tile, and check which one(s), if any, is/are designated "enemies")

My problem is that I'm also using a pixel movement plugin (Altimit Movement), which makes pinning down events to an appropriate tile trickier. My guess is that it's just finnicky, because sometimes when I click on an event during playtesting, it returns my test text (meaning the script call in the parallel common event successfully identified and returned that event's ID in the array) - but most of the time, it doesn't. I imagine this is just an inherent aspect of trying to check for events in a grid-based way, when those events have grid-free movement.

So a potential solution I thought of would be to check for not just the tile clicked, but each tile surrounding it, as well, to give more spatial leeway to the player's click (I know this would result in a much wider margin of error, but that's okay for my purposes - the point is to allow the player to easily choose a target, not to test their coordination/reflexes). Thing is, I don't have enough JS knowledge to have any idea how to approach doing this.

Could the script call I'm using potentially be altered to check multiple tiles for event IDs at once, perhaps by utilizing arrays for the x and y parameters? If this is possible, how would I write such code (to have it check each of those tiles)?

Or, does it have to be done by separately checking the clicked tile and each of the 8 tiles surrounding it? If this is the case, what code would I need to add the contents of each subsequent, resulting array to the same variable
(so I can check all the returned event IDs at once, rather than from 9 separate variables)?

Ultimately, I just need to be able to retrieve the IDs of any events on or immediately near (so the targeting is less precise/finnicky) the spot where the player clicked.


I mostly just gave background so there's context of what I'm trying to do, since I know that's helpful, even though the root of the question is pretty straight-forwardly a "how do I write this in JavaScript" one. However, if based on the background you think there might be a better/more efficient way to go about implementing this clicking feature, I can provide screenshots of the event pages I currently have if needed/requested.

Thanks so much for any help and insight!
I guess they count as being on the next tile if they've moved even a little bit off of it. You can instead try something like this.

JavaScript:
Game_Map.prototype.eventsXy_special = function(x, y) {
    var MinX = x - 0.5;
    var MaxX = x + 0.5;
    var MinY = y - 0.5;
    var MaxY = y + 0.5;
    var arr = [];
    this.events().filter(function(event) {
        if (event._realX > MinX && event._realX < MaxX &&
            event._realY > MinY && event._realY < MaxY)) {
            arr.push(event);
        }
    });
    return arr;
};

Game_Map.prototype.eventIdXy_special = function(x, y) {
    var arr = [];
    var list = this.eventsXy_special(x, y);
    if (list.length > 0) {
        for (var i = 0; i < list.length; i++) {
            arr.push(list[i].eventId());
        }
    }
    return arr;
};
The way I see it, your question has 2 aspects to it:
  1. How to run the same code multiple times but with different x and y values.
  2. How to combine the results of multiple function calls that return an array.

Let's start with the easier of both problems: combining arrays. This is known as a "concatenation", and there's a function for that in JavaScript: Array.concat(otherArray)

Here's an example of how to use it:
JavaScript:
let result1 = $gameMap.eventIdXy_special(x1, y1);
let result2 = $gameMap.eventIdXy_special(x2, y2);

let result = result1.concat(result2);


As for running the function multiple times with different values, this is very basic, but can become quite complex depending on the use case. For that, you need a for loop.

Here's one example:
JavaScript:
const x = 10;
const y = 10;
let result = []; // Initialize with empty array
for (let offsetX = -3; offsetX <= 3; offsetX++) {
    result = result.concat($gameMap.eventIdXy_special(x + offsetX, y));
}
// Do something with result

This will loop through all x values from x - 3 to x + 3, centered around x = 10 and y = 10. The for loop is read as follows: Starting with offsetX at -3, execute the loop as long as offsetX is smaller or equal 3, and increment offsetX by 1 at the end of each run of the loop.

But what do we do if the player clicks near the edge of the map? For example, x = 2? The game might crash if it tried to access coordinate -1, since that coordinate doesn't exist. Fortunately, it seems this won't be a problem. Game_Map.prototype.eventIdXy_special() uses Game_Map.prototype.eventsXy_special(), which uses Game_CharacterBase.prototype.pos(), which simply checks whether its own x and y coordinates match the x and y values given. In this case it doesn't matter if you're asking for a negative value; the values either match the coordinates, or they don't.

Now, you probably want to check multiple y values as well. For that, we simply need another loop (this time for y) running inside the existing loop. The simplest is to check in a square around x and y:
JavaScript:
const x = 10;
const y = 10;
let result = []; // Initialize with empty array
for (let offsetX = -3; offsetX <= 3; offsetX++) {
    for (let offsetY = -3; offsetY <= 3; offsetY++) {
        result = result.concat($gameMap.eventIdXy_special(x + offsetX, y + offsetY));
    }
}
// Do something with result

In other words: for each x position between x - 3 and x + 3, check each y position between y - 3 and y + 3.

But what if you want to check in a diamond instead? For example, instead of checking:
Code:
OOOOOOO
OOOOOOO
OOOOOOO
OOOXOOO
OOOOOOO
OOOOOOO
OOOOOOO
we want to check:
Code:
   O
  OOO
 OOOOO
OOOXOOO
 OOOOO
  OOO
   O

This is where it gets more complex:
JavaScript:
const x = 10;
const y = 10;
let result = []; // Initialize with empty array
for (let offsetX = -3; offsetX <= 3; offsetX++) {
    const maxYOffset = 3 - Math.abs(offsetX);
    for (let offsetY = -maxYOffset; offsetY <= maxYOffset; offsetY++) {
        result = result.concat($gameMap.eventIdXy_special(x + offsetX, y + offsetY));
    }
}
// Do something with result

Here we calculate the absolute value of offsetX (giving us a positive number), and use that to tweak the range of our offsetY. For example, if offsetX is -3 or 3, offsetY will be 3 - 3 = 0. If offsetX is -2 or 2, offsetY will be 3 - 2 = 1 instead. If offsetX is -1 or 1, offsetY will be 3 - 1 = 2, and finally, if offsetX is 0, offsetY will be 3 - 0 = 3. This gives us the diamond shape we want.

And what if we want a circular shape? Then we need the help of Pythagoras.

According to him, in a triangle with sides a, b and c, and a right angle (90°) opposite side c, the lengths of a, b and c satisfy the following formula: a² + b² = c².

This is useful to us, because a and b are basically x and y, and c is the distance to the center, which in a circle is always the same.

So, since we defined c = 3 and we know x (from the first loop), we need to calculate the range of y for the second loop. The formula is: y² = c² - x² or y = √(c² - x²).

As you can tell, we'll get fractional numbers, but our tiles use full numbers (also known as "integers"), so we'll need to use a rounding function. There are multiple such functions in JavaScript. Here are a few:
  • Math.round() gives us the nearest integer. If the number is a multiple of 0.5, the function will return the highest nearest integer. For example: 2.5 -> 3 and -2.5 -> -2.
  • Math.floor() always rounds down to the nearest smaller integer. For example: 1.9 -> 1 and -1.1 -> -2.
  • Math.ceil() always rounds up to the nearest larger integer. For example: 2.1 -> 3 and -2.9 -> -2.
There's also "round away from 0" and "round towards 0", but we'd have to implement those functions ourselves and there is little reason to do so.

Now let's try and implement this:
JavaScript:
const x = 10;
const y = 10;
let result = []; // Initialize with empty array
for (let offsetX = -3; offsetX <= 3; offsetX++) {
    const maxYOffset = Math.floor(Math.sqrt(9 - offsetX * offsetX));
    for (let offsetY = -maxYOffset; offsetY <= maxYOffset; offsetY++) {
        result = result.concat($gameMap.eventIdXy_special(x + offsetX, y + offsetY));
    }
}
// Do something with result

The only line that changed is the one where we define maxYOffset. I decided on Math.floor() as my rounding function, but you may use whatever function best suits your needs. As you can probably guess, Math.sqrt() is the square root function. Finally, I didn't use Math.abs() this time, because if you multiply a negative number with another negative number, the result becomes positive, so there's no need to waste time on calculating the absolute value in this case.

If you're curious, this is what our circle solution will check:
Using Math.floor():
Code:
   O
 OOOOO
 OOOOO
OOOXOOO
 OOOOO
 OOOOO
   O

Using Math.round():
Code:
   O 
 OOOOO
OOOOOOO
OOOXOOO
OOOOOOO
 OOOOO
   O

Using Math.ceil():
Code:
   O 
OOOOOOO
OOOOOOO
OOOXOOO
OOOOOOO
OOOOOOO
   O

Looks like Math.round() is closer to a circle than the other two...


I hope this was at least somewhat helpful.
I lost much Data and i cannot realy use the Syntax myself, but here is something that maybe helps:

Use ScreenX and Y Coordinates instead of Map Grid Coordinates for your Hit detection, that will solve the Bug you ran into.

The following Scriptline Code checks if Event1 is ontop of event id 2 to 100. If yes it activates the self switch of the hit Events, which could be id2 to id100.
The Center Pixel of the Event Box is its Screencoordinate. In the conditional branch iam asking if center of event1 is not more than 20 Pixels away from the centers of each single event from 2 to 100.
event1 screen x and y could be exchanged with your mouse screen x and y. And the distance maybe a bit increased.

The code should work as copy paste. Maybe you are able to edit your mouse screen x and y coordinates into it yourself, else let us know.

Code example:

Code:
for (a = 2; a < 100; a++) {
if (!!$gameMap.event(a)) {   // check that event exists
hitDist = Math.abs($gameMap.event(a).screenX() - $gameMap.event(1).screenX()) +
          Math.abs($gameMap.event(a).screenY() - $gameMap.event(1).screenY());
if (hitDist <= 20) {  // in range?
$gameSelfSwitches.setValue([$gameMap.mapId(), a, 'A'], true);
 }}}

Edit: Thisway 1 Parallel Event can check for Every Event on the Map.
Edit2: Thank you @caethyril for the Code and Syntax Help over the Years in the Forums.
Thank you guys SO MUCH for these answers!!

@MechPen I tried this when you posted it, but unfortunately it still didn't work - which made me think it was less about providing a margin of error and more about the script call just struggling to detect events that aren't exactly on a tile. Which kind of goes along with what @Bex said here:

Use ScreenX and Y Coordinates instead of Map Grid Coordinates for your Hit detection, that will solve the Bug you ran into.

So while MechPen's edit of the script didn't work for this particular situation, it did basically tell me what was going wrong and that I needed to go in a different direction altogether (i.e. not using the $gameMap.eventIdXy function at all). So thank you for that! 🙂

I'll admit I only skimmed @Nolonar 's solution when it was posted, because by then I had already resolved to find a different way to make it work, had a new script well underway, and somehow ended up teaching myself how to make a proper plugin for it. While the $gameMap.eventIdXy part isn't applicable anymore, HOLY COW this post is actually SO helpful and informative!!! All the math, functions, and examples of logic are incredibly valuable, and will 100% come in handy when I get around to coding things like AOE effects 👋

Then Bex replied, and I only just now saw it because I've been knee-deep in writing my new plugin, for the past 48 hours (outside of school) at the least 😊I learned the ropes and got it working within the first 24, but I've also been having a lot of fun expanding it to include the further processes for which I needed this function in the first place (that were originally dispersed among many separate common events/event pages). It's pretty tailored to my specific purposes, but I also kind of wanna make a more generic version (with more customizable parameters, etc.) to post for other people to check over and/or use, as well 😤

Anyway, the general method I went with is basically exactly what Bex suggested! And I can confirm that it works like a charm!! Once I finish up and polish this plugin, I'll probably post it for feedback~

So thanks all, once again! And just one more shoutout to Nolonar for providing such a long, thoroughly educational reply 😍

Original thread: https://forums.rpgmakerweb.com/threads/solved-can-i-make-this-script-call-check-more-than-one-tile.146436/