I have a program where an entity moves around in two-dimensional space. To move one step, the entity picks its next point, and then sets it as his current point.
Sometimes, however, the entity’s next point lies in an Area (java.awt.geom.Area) that is forbidden (the “forbidden area” is actually a velocity obstacle).
How can the entity pick the point outside the Area which is closest to the entity’s preferred point?
The Area is composed of different shapes (sometimes, the shapes are not touching).
My initial plan was to simply draw a line to the preferred point. Wherever the line intersected the Area first, this would be the next-best point. However, finding the intersection between a line and an Area turns out to be quite complex.
EDIT: This wouldn’t necessarily find the closest point. This would just find the closet point on the same trajectory. I’m looking for the closest possible point.
Perhaps Area isn’t the best class to use. All I require is something that can add multiple shapes, even when the shapes aren’t touching.
I’ve solved the problem:
First, find all the line segments that constrain the
Area. I’ve written code to do that on a different answer.Then, it’s just a matter of iterating through each line segment, and recording the point on the segment that’s closest to the entity’s desired point. Store these in the data structure of your choice (e.g., an
ArrayList).See: Shortest distance between a point and a line segment
Lastly, determine which of the points is closest to the desired point. Voilà!
Here’s a demonstration:
Here’s the result:
And again: