In my 2D environment a player can move diagonally, horizontally and vertically. When looking at the grid below you can see that the player (marked as x) can move to 8 different spots from where he (or she xD) is now.
1 | 2 | 3
-----------
4 | x | 5
-----------
6 | 7 | 8
Instead of storing this as (which is a lot of data):
Go1 = true;
Go2 = true;
Go3 = true;
Go4 = true;
Go5 = true;
Go6 = true;
Go7 = true;
Go8 = true;
I think it’s better to first convert it to:
11111111
..which represents 8 times true. With that in mind and the knowledge that the decimal representation of the binary number 11111111 (8 bit) equals the nummer: 255 I rather convert it and store the current-possible-places-to-move-to as 255.
Code:
x = parseInt(11111111);
var bin = x.toInt(2);
document.write(bin);
That means that if there’s a wall at (for example) location (1, 4 and 6) = left side from player, the player can only move to:
01101011
Which can be stored as: 107.
Let’s say that the player wants to move to location 3. This means that my script has to do the following:
- convert the 3 digit current-possible-places-to-move-to number back to binary
- get the 3rd number from that binary code
- check if that number is a 1 or 0
Question:
Is it possible to calculate this without converting to binary back and forth in Javascript? If yes, how?
Bit-shift so that the relevant digit is the least significant, and then test the parity of the value:
This will return value at the specified position, counting from the left starting the index at 1.