dmetal23
dmetal23

Reputation: 141

Checking if a point is inside or outside a polygon for an ArrayList

I want to be able to check if a user inputted point is inside or outside a bounded set of points.I am aware of the .contains function for the Polygon class in java, but I was wondering how I would go about doing something like that for an ArrayList of < Point > .

Here is an example of what I'm trying for:

The points of the polygon are: (-10, 0) (-1, -10) (0, 10) (1, -10) (10,0)

Test point: 5 0

Inside

Test point: 8 8

Outside

Any hints in the right direction would be appreciated!

Upvotes: 1

Views: 201

Answers (1)

Ideasthete
Ideasthete

Reputation: 1541

This seems a little homeworky, so I am not going to go into great detail, but assuming that the polygon points listed are always in order, you could connect lines between all the points in the polygon to close its border, then cast rays from your sample points outward. If the ray passes through an odd number of lines before going outside the area the polygon is in, that means the sample point is inside the polygon. If it passes through an even number of lines, it is outside the polygon. (If it never goes through a line, it is also outside the polygon, assuming the ray is long enough to hit the edge of the polygon from where the sample point is located.) Best of luck.

More Information

Upvotes: 1

Related Questions