If int is 0 for north, 1 for east, etc .... How do I change direction?

I am creating a program, and I need to follow the direction that the object is facing. (north, east, south, west)

I'm not sure if this is even the best way to do this, so correct me if necessary, please.

In some cases, I need to turn left or right, and even in the opposite direction. What is the easiest way to achieve this?

This is in Java, and I cannot use anything imported.

+4
source share
3 answers

Assuming the numbers are as follows:

0 - North | 1 - East | 2 - South | 3 - West

Then run it through the algorithm

int reverse = (direction + 2) % 4; 

should give the opposite direction.

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 easy as adding or subtracting, and then with module 4, to make sure it goes back.

 int left = (direction +3) % 4; int right = (direction + 1) % 4; 
+10
source

Using an enumeration type with the values ​​NORTH, EAST, SOUTH, WEST:

If

 NORTH=0 EAST=1 SOUTH=2 WEST=3 

Rotation rule -

 (dir + 1) % 4 

Turn left -

 (dir + 3) % 4 

Reverse direction

 (dir + 2) % 4 

Note. In general, when you want to be able to add integers and wrap them (2, 3, 0, 1, 2, 3, 0, ...), you need to use the modulo operator (%).

+3
source
 int left = (direction + 3) % 4; int behind = (direction + 2) % 4; int right = (direction + 1) % 4; 
0
source

Source: https://habr.com/ru/post/1442630/


All Articles