Say you're creating a game like Fire Emblem, but you dont know how to determine what squares a player can and can't move to based on their position and their speed. This should help
Lets say that we have a 5x5 tile map, and the player can move up to 2 squares per turn.
Map:
0 [ ][ ][ ][ ][ ]
1 [ ][ ][ ][ ][ ]
2 [ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ]
0 1 2 3 4
Lets place our character at 2, 3, and our speed (squares per turn that can be moved) to 2, so here's what the player can move to:
[ ][ ][ ][ ][ ] | KEY
[ ][ ][x][ ][ ] | o: Player
[ ][x][x][x][ ] | empty: Player can't move here
[x][x][o][x][x] | x: Player can move here
[ ][x][x][x][ ] |
Now, here's how to find out if a tile can or cannot be moved to:
(Tile X) - (Player X) = (Relative Tile X)
(Tile Y) - (Player Y) = (Relative Player Y)
(Relative Tile X) + (Relative Tile Y) = (Relative Tile Position)
If (Relative Tile Position) is less than or equal to speed, the player can move there
so, to check if we can move to 4, 4 (bottom-right tile; which we can't move to), you do this
Speed: 2
Player X: 2
Player Y: 3
Tile X: 4
Tile Y: 4
4 - 2 = 2 (Relative Tile X Position)
4 - 3 = 1 (Relative Tile Y Position)
2 + 1 = 3 (Relative Tile Position)
If 3 <= 2
Player Can Move Here
Otherwise
Player Cannot Move Here
Because 3 is not less than or equal to 2, the player cannot move to the tile 4, 4 in this turn
Lets use another tile and player location. Lets say the player is at 0, 0, and we want to test tile (2, 1) and the player has a speed of 4
Speed: 4
Player X: 0
Player Y: 0
Tile X: 2
Tile Y: 1
2 - 0 = 2 (Relative Tile X)
1 - 0 = 1 (Relative Tile Y)
2 + 1 = 3 (Relative Tile Position)
if 3 <= 4
Player Can Move Here
otherwise
Player Cannot Move Here
Because 3 is less than 4, the player can move here.
Hope this helps!