# Get next tile by given angle

I am new to game development, and I have been building some game with LibGDX engine.

The following function might make you feel bad

The function I am going to show, is accepting the current rotation index of my player (player has 4 rotations, north, south, west, east). The function will return how much to jump in X to get the next tile according to his direction (angle) and the selected move (you can only select left, right or forward per turn):

public int getIncrementXForRotation(int rotationIndex) {
switch(this) {
case MOVE_FORWARD:
switch(rotationIndex) {
case Face.EAST:
return 1;
case Face.SOUTH:
return 0;
case Face.WEST:
return -1;
case Face.NORTH:
return 0;
}
case MOVE_BACKWARD:
switch(rotationIndex) {
case Face.EAST:
return -1;
case Face.SOUTH:
return 0;
case Face.WEST:
return 1;
case Face.NORTH:
return 0;
}
case MOVE_LEFT:
switch (rotationIndex) {
case Face.EAST:
return 0;
case Face.SOUTH:
return 1;
case Face.WEST:
return 0;
case Face.NORTH:
return -1;
}
case MOVE_RIGHT:
switch (rotationIndex) {
case Face.EAST:
return 0;
case Face.SOUTH:
return -1;
case Face.WEST:
return 0;
case Face.NORTH:
return 1;
}
case TURN_LEFT:
switch(rotationIndex) {
case Face.EAST:
case Face.SOUTH:
return 1;
case Face.WEST:
case Face.NORTH:
return -1;
}

case TURN_RIGHT:
switch(rotationIndex) {
case Face.NORTH:
case Face.EAST:
return 1;
case Face.WEST:
case Face.SOUTH:
return -1;
}
}
return 0;
}


Same function for Y.

Now I looked at this, and i thought to myself.. north can be an 0, and east can be 90, and south can be 180 and west can be 270, am I right?

So there is a way to mathematically do these coordinate increment according to the angle, isn't there?

The reason I classified my player angles by enums is because each direction is an image.


Yes, you can do it with angles. However it's also easy to do it with a table. The main idea is to be consistent with directions, using 0, 1, 2, 3 in either clockwise or counterclockwise order. That way you can add directions together to represent rotations.

With tables:

int dx[4] = [1, 0, -1, 0];
int dy[4] = [0, 1, 0, -1];

public int getIncrementXForRotation(int rotationIndex) {
/* let's assume your enum is
MOVE_FORWARD = 0, MOVE_RIGHT = 1, MOVE_BACKWARD = 2, MOVE_LEFT = 3
and FACE_EAST = 0, FACE_SOUTH = 1, FACE_WEST = 2, FACE_NORTH = 3
*/
int dir = (int(move_direction) + rotationIndex) % 4;
return dx[dir];
}


With angles, if 0 = east, 1 = south, 2 = west, 3 = north, you can use dx = Math.cos(direction * Math.PI/2), dy = Math.sin(direction * Math.PI/2).

Depending on the orientation of your axes, you may have to flip the y direction (use -Math.sin instead of Math.sin).