如何获得线性阵列的坐标

时间:2011-09-14 15:31:03

标签: java arrays

我正在制作一个游戏,其中我将一个3d地图存储在一个数组整数中:

int width = 256;
int height = 256;
int depth = 64;
int[] map = new int[width * height * depth];

我需要能够获得索引的x,y,z。我想出的当前方法是:

private int getX(int blockID) {
    return blockID % width;
}

private int getY(int blockID) {
    return (blockID % depth) / height;
}

private int getDepth(int blockID) {
    return blockID / (width * height);
}

获取x和深度的方法似乎工作,但我不能让getY()正常工作,我不断得到和ArrayIndexOutOfBoundsException如下所示:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at game.Level.updateLighting(Level.java:98)
at game.Level.generateMap(Level.java:58)
at game.Level.<init>(Level.java:21)
at game.mainClass.main(Minecraft.java:6)

如果您知道如何操作,请提供帮助。

2 个答案:

答案 0 :(得分:3)

多德。只需使用3D阵列。

int[][][] map = new int[width][height][depth];

然后,您不必担心x中的yzblockID索引的转义。他们是独立的,所以保持这种方式。

答案 1 :(得分:1)

尝试

private int getY(int blockID) {
    return (blockID / width) % height
}
相关问题