Thursday, May 21, 2015

geometry - How can I tell whether an object is moving CW or CCW around a connected path?


Lets say we have a jagged shape:


shape0



And two creatures moving along it's outline.


Then we smooth the shape completely by pulling the corners out.


We get this:


smooth


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


enter image description here



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.


example



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

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...