My game is made up of chunks which are identified in world space with and X and Y coordinate. Each chunk contains 16 tiles by 16 tiles by 4 layers. So that I don't have to loop over every single tile every time I want to access things such as hitboxes or animation frames I store that tile's value as keys in various dictionaries such as "Animations" or "Collidables". Until now I have been doing it like this:
public string GetTileKey(int layer)
{
string XString = X.ToString();
if (XString.Length < 4)
{
XString = XString.PadLeft(4, '0');
}
string YString = Y.ToString();
if (YString.Length < 4)
{
YString = YString.PadLeft(4, '0');
}
return layer.ToString() + XString + YString;
}
which as you can imagine, slows things down considerably!
After chatting with a few awesome people in discord I was suggested a bitwise method which would store the first few bits as the X coordinate, the second few as the Y, and the last 2 as the layer like so:
public int GetTileKeyAsInt(int layer, IInformationContainer container)
{
return (X << 16) | (Y << 9) | layer;
}
(The container parameter is not currently used, I was trying things out with its X and Y coordinates. It's really just the chunk)
which works fantastic when used with X and Y values which are between 0 and 128 and which are not negative. In addition it guaranteed no duplicate keys.
I quickly realized this wouldn't work with my world, which requires both positive and negative coordinates and an "infinitely" expanding number of chunks.
What is a better way to do this? I was planning on using a float or a double and using the first bit as the sign value, and the next eight (4 and 4) to store the X and Y coordinates of local tiles within chunks and then allocating the rest of the bits to allow for a massive number of allowable chunks. I'll admit I'm not super familiar with bitwise operations or even really the specifics between int, float and double :( but from what I've gathered it doesn't actually make sense to do bitwise operations with anything larger than an Int 32!