Need help with grid code

You triangles are arranged in a grid.

Calculate the grid square your point is in with math.

Check the two triangles in that grid square and the triangles in the surrounding eight quads as well just in case the points have shifted in the XZ plane a lot.

Like take this image example:

Purplish lines are the original positions of your triangles, before your waves moved them around.

Your goal is to find the triangle the red dot sits on.

First you find the grid square the red dot is on with some simple math

local offset = dot - GRID_ORIGIN
local row = 1 + math.floor(offset.Z / GRID_SQUARE_SIDE)
local col = 1 + math.floor(offset.X / GRID_SQUARE_SIDE)

Cool, now you know the red dot’s in the middle square. Check if it’s actually on top of one of those two triangles with your PointWithinArea function (it’s not).

Then check the other triangles in the immediately neighboring squares as well. Eventually you’ll figure out it’s in the bottom-left triangle in the upper neighbor, and you’re done.

You only have to check 16 triangles in the worst case, which is really quick. Expand the “ring” of triangles you check if your vertices are getting offset by more than a single grid row width.