I have a polygon of 2D points. I can test if a point is in/on the polygon. I need to solve the problem of, given a 2D point and a bearing (0 to 360 where 0 is positive y axis going clockwise), find the intersection point, if any.
For example, if my polygon is a square, of [(0,0), (4, 4), (4, 0), (0, 4)], and my point (inside the polygon) is (2, 2) with a bearing of 90 degrees, the intersection point would be (4, 2). If my point is (6, 2), bearing of 270 I would get the same point. Now, if my point (6, 2) and a bearing of 90, I would never intersect the polygon.
I need to program this, so is there any formula, logic that I can use?
I started with the formula for the bearing = atan2(Ix - Px, Iy - Px) where I is unknown intersection, P is known point. But I need one more equation to solve for the 2 unknowns.
Point outside but no intersection
These pictures outline a very simple example, my polygon may be irregular and my bearing may be anywhere between 0 and 360.
The initial starting point and heading define a ray.
The polygon is made of a bunch of line segments. So what you can do is check if each line segment intersects with your ray.
(To check if a line segment intersects with your ray, extend the line segment and ray into infinite lines and find their intersection.
(Finding the intersection is fairly simple with infinite lines, though you will have some edge cases to handle if the two lines are parallel: you will have either zero points of intersection, or infinitely many.)
To check if the intersection lies on the line segment, use your function that tells you whether or not it lies on the boundary of the polygon. To check whether the intersection lies on the ray, do the following:
Let $P$ be the starting point, let $I$ be the proposed intersection point. Let $\vec{v}$ be the vector pointing from $P$ to $I$. And let $\hat{h}$ be the unit vector pointing in the direction of the heading. Then we want to make sure that $\vec{v}\cdot\hat{h} \geq 0$.)
This will give us a list of points where the ray intersects with the polygon. Either the list is empty, in which case we are done, or the first point of intersection can be found by choosing the point that is nearest to the starting point, $P$.