Most efficient way to handle coordinate maps in Java
Posted
by
glowcoder
on Game Development
See other posts from Game Development
or by glowcoder
Published on 2011-02-26T17:24:55Z
Indexed on
2011/02/26
23:33 UTC
Read the original article
Hit count: 324
I have a rectangular tile-based layout. It's your typical Cartesian system.
I would like to have a single class that handles two lookup styles
- Get me the set of players at position X,Y
- Get me the position of player with key K
My current implementation is this:
class CoordinateMap<V> {
Map<Long,Set<V>> coords2value;
Map<V,Long> value2coords;
// convert (int x, int y) to long key - this is tested, works for all values -1bil to +1bil
// My map will NOT require more than 1 bil tiles from the origin :)
private Long keyFor(int x, int y) {
int kx = x + 1000000000;
int ky = y + 1000000000;
return (long)kx | (long)ky << 32;
}
// extract the x and y from the keys
private int[] coordsFor(long k) {
int x = (int)(k & 0xFFFFFFFF) - 1000000000;
int y = (int)((k >>> 32) & 0xFFFFFFFF) - 1000000000;
return new int[] { x,y };
}
}
From there, I proceed to have other methods that manipulate or access the two maps accordingly.
My question is... is there a better way to do this? Sure, I've tested my class and it works fine. And sure, something inside tells me if I want to reference the data by two different keys, I need two different maps. But I can also bet I'm not the first to run into this scenario.
Thanks!
© Game Development or respective owner