Just so that you know what I mean, the following is a complete working but unaccelerated method to find the nearest intersection of a ray with a polygon, given as a sequence of (x, y) coordinate pairs in a float array, by testing the ray against all line segments of pairwise vertices.
The method returns the index of the first vertex of the nearest polygon edge the ray intersected with, if any, or -1 if none.
The second index would always be the first index + 1 (modulus the vertex count).
So if your polygon were a rectangle and the ray intersected the “last edge” of the polygon, the method would return 3, and your second vertex would be 0 (= (3+1) % 4).
Also it optionally writes the point of intersection into the supplied vector ‘p’.
public static int intersectPolygonRay(float[] verticesXY, float originX, float originY, float dirX, float dirY, Vector2f p) {
float nearestT = Float.MAX_VALUE;
int count = verticesXY.length >> 1;
int j = count - 1;
int edgeIndex = -1;
for (int i = 0; i < count; i++) {
float aX = verticesXY[j<<1], aY = verticesXY[(j<<1) + 1];
float bX = verticesXY[i<<1], bY = verticesXY[(i<<1) + 1];
float v1X = originX - aX, v1Y = originY - aY;
float v2X = bX - aX, v2Y = bY - aY;
float invV23 = 1.0f / (v2Y * dirX - v2X * dirY);
float t = (v2X * v1Y - v2Y * v1X) * invV23;
float t2 = (v1Y * dirX - v1X * dirY) * invV23;
if (t >= 0.0f && t2 >= 0.0f && t2 <= 1.0f && t < nearestT) {
edgeIndex = j;
nearestT = t;
p.x = originX + t * dirX;
p.y = originY + t * dirY;
}
j = i;
}
return edgeIndex;
}