Determining the direction of the turn?
I want to rotate an object clockwise or counterclockwise. A pair of integers (0 through> 7) represents the direction the object is aiming towards (for example, left, left, up, vertical, right, ...). Adding +1 to the object's current direction rotates it clockwise, subtracting -1 rotates it counterclockwise.
If I want the object to turn in a specific direction (= integer), how do I determine the minimum number of turns needed?
I am currently using this way of thinking:
int minimumRequiredTurns = min(abs(currentDirection.intvalue - goalDirection.intvalue),
8 - abs(currentDirection.intvalue - goalDirection.intvalue));
Can I do this without instructions min
?
source to share
I think,
(1-(abs(abs(currentDirection.intvalue - goalDirection.intvalue)/(n/2)-1)))*(n/2)
should do the trick, where n
is the number of possible directions.
To only have whole calculations, convert this value to
(n/2)-abs(abs(currentDirection.intvalue - goalDirection.intvalue)-(n/2))
Explanation: Using the hat function to generate the map:
0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 3
6 -> 2
7 -> 1
source to share
Almost certainly a much better design would use vectors to represent directions ; treat "direction" as a pair of numbers (x,y)
, so that x
represents the horizontal direction, y
represents the vertical.
So (1,0)
will represent the opposite to the right; (0,1)
will be displayed upwards; (-1, 0)
will stand on the left; (1,1)
will stand up and right; and etc.
Then you can just use the normal vectorial solution for your problem: take the direction you are facing and the direction you want to face and take the cross product of the two.
result = x1y2 - x2y1
If the result is positive, turn it counterclockwise; if negative, turn clockwise (this works because of the correct right-hand rule that defines cross products).
Note that this approach is trivially generalized to allow arbitrary directions, not just horizontal / vertical / diagonal.
source to share
No min
, no abs
, one expression, no division:
turns = ((((goalDirection + 8 - currentDirection) % 8) + 4) % 8) - 4
How it works: The innermost expression (goalDirection + 8 - currentDirection)
is the same as given by AShelley; number of revolutions required clockwise. The outermost expression displaces this by the equivalent in [-4 .. + 3]
source to share