Lets say we have a jagged shape:
And two creatures moving along it's outline.
Then we smooth the shape completely by pulling the corners out.
We get this:
It is easy to see now that Orange is moving CW and green CCW. How can I tell in which direction they are moving without smoothing out the shape?
New image
Answer
Draw a line to infinity and count how many times you cross the shape (even or odd), not counting the segment where the creature lies. Then check whether the creature is going left or right of that line.
In this example, we cross the shape twice (so even) and we go to the left. The result is immediate from this table:
# Crosses | even | odd
Direction | |
-------------+-------+------
left | CCW | CW
right | CW | CCW
In pseudocode:
x, y = position of creature
vx, vy = direction of creature movement
crossings = 0
for each x1, y1, x2, y2 in shape segments:
if (x1 < x and x <= x2) or (x2 < x and x <= x1):
if y - y1 > (x - x1) * (y2 - y1) / (x2 - x1):
++crossings
if (crossings & 1) == (vx < 0):
return CW
else
return CCW
No comments:
Post a Comment