Reputation: 31
I have been developing a game for canvas in JavaScript.
I have chosen to create the game without limitations to the world size grid. So if they wish to play with a grid size of N, the logic will generate it.
I have been working with bounds detection and have begun to program a function that will change the cell location on the grid if the user decides to travel outside the screen.
For simplicity sake, I have shrunk the grid size to N = 9 so you can visualize this. The grid looks like
[0][1][2]
[3][4][5]
[6][7][8]
If the user is to travels off a -x value Cell[0], they will appear at the rightmost x position of cell [2]. this is represented as SQRT(N). So I know that the rightmost corner is SQRT(N). I also know that N is the bottom right hand cell [8].
With that said, here is a sample of the cells and thier equation IDs.
[0][1][SQRT(N)]
[3][4][5]
[N - SQRT(N)][7][N]
The grid above shows the x axis formulas for the 4 corners, but it is essential that I at least try to answer the inner cell equations before using static magic number switch-case conditionals.
here is some javscript code showing what I am explaining:
if (player.X < 0 - 10) {
player.X = SCREEN_WIDTH;
if (gameQuadrent == 0) {
gameQuadrent = Math.floor(Math.sqrt(WORLD_SIZE));
} else if (gameQuadrent == (WORLD_SIZE - Math.floor(Math.sqrt(WORLD_SIZE)))) {
gameQuadrent = WORLD_SIZE;
} else {
gameQuadrent--;
}
}
Any more efficient ways of doing this? I am trying to solve this problem without having to move over to a fixed world size.
Much Appreciated.
Upvotes: 1
Views: 241
Reputation: 338
Quadrent is on the left boundary of the world if it's number is a multiple of SQRT(WORLD_SIZE). Therefore the following code should update the gameQuadrent accordingly.
int side = Math.floor(Math.sqrt(WORLD_SIZE));
if (gameQuadrent % side) == 0) {
gameQuadrent += side - 1;
}
else {
--gameQuadrant;
}
Upvotes: 2