I'm creating a program, and I need to keep track of which direction an object is facing. (north, east, south, west)
I'm not sure if this is even the best way to do that, so correct me on that if necessary, please.
In some instances, I'll need to turn left or right, and even reverse direction. What is the easiest way to achieve that?
This is in Java, and I can't use anything that is imported.
Assuming the numbers are as such:
0 - North | 1 - East | 2 - South | 3 - West
Then running it through the algorithm
int reverse = (direction + 2) % 4;
should yield the reverse direction.
Let's test it:
North: 0 + 2 = 2. 2 % 4 = 2: South
South: 2 + 2 = 4. 4 % 4 = 0: North
East: 1 + 2 = 3. 3 % 4 = 3: West
West: 3 + 2 = 5. 5 % 4 = 1: East
Success!
Turning left and right is as simple as adding or subtracting, then taking the modulus of 4 to make sure it loops back around.
int left = (direction +3) % 4;
int right = (direction + 1) % 4;
Using an enum type with values NORTH, EAST, SOUTH, WEST:
If
NORTH=0
EAST=1
SOUTH=2
WEST=3
Turning right is
(dir + 1) % 4
Turning left is
(dir + 3) % 4
Reversing direction is
(dir + 2) % 4
Note: In general, when you want to be able to add to integers and have them wrap around (2, 3, 0, 1, 2, 3, 0, ...) you need to use the modulo operator (%).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With