ArrayIndexOutOfBound错误 – Java
我得到一个奇怪的错误,我不知道为什么有人可以找到错误的位置?
错误:
Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: -61 at ca.serict.game.gfx.Screen.render(Screen.java:55) at ca.serict.game.entities.Player.render(Player.java:57) at ca.serict.game.level.Level.renderEntities(Level.java:67) at ca.serict.game.Game.render(Game.java:168) at ca.serict.game.Game.run(Game.java:127) at java.lang.Thread.run(Unknown Source)
如果您需要查看来自任何这些行的代码,请列出错误,请告诉我。
Screen.java第55行:
int col = (colour >> (sheet.pixels[xSheet + ySheet * sheet.width + tileOffset] * 8)) & 255;
Player.java第57行:
screen.render(xOffset, + modifier, yOffset, (xTile + 1) + yTile * 32, colour);
Level.java第65行 – 69:
public void renderEntities(Screen screen) { for (Entity e : entities) { e.render(screen); } }
Game.java第168行:
level.renderEntities(screen);
Game.java第157 – 128行:
if (shouldRender) { frames++; render(); }
屏幕55的公共虚空:
public void render(int xPos, int yPos, int tile, int colour, int mirrorDir) { xPos -= xOffset; yPos -= yOffset; boolean mirrorX = (mirrorDir & BIT_MIRROR_X) > 0; boolean mirrorY = (mirrorDir & BIT_MIRROR_Y) > 0; int xTile = tile % 32; int yTile = tile / 32; int tileOffset = (xTile << 3) + (yTile << 3) * sheet.width; for (int y = 0; y < 8; y++) { if (y + yPos = height) continue; int ySheet = y; if (mirrorY) ySheet = 7 - y; for (int x = 0; x < 8; x++) { if (x + xPos = width) continue; int xSheet = x; if (mirrorX) xSheet = 7 - x; int col = (colour >> (sheet.pixels[xSheet + ySheet * sheet.width + tileOffset] * 8)) & 255; if (col < 255) pixels[(x + xPos) + (y + yPos) * width] = col; } } }
所以你使用这个表达式计算你的数组索引:
xSheet + ySheet * sheet.width + tileOffset
您需要确保该值在数组sheet.pixels
的范围内。 为此,您可以编写一个小方法来钳制索引:
public int clamp(int index, int start, int end) { return index > end ? end : index < 0 ? 0 : index; }
并使用它:
int i = clamp((xSheet+ySheet*sheet.width+tileOffset), 0, sheet.pixels.length-1) sheet.pixels[i];
这样你就可以确保索引在[0,sheet.pixels.length-1]范围内,但是你仍然需要知道这对你的用例是否有意义。
理想情况下,我们将获得Screen:55的代码。 但它看起来像你是访问数组之外的元素。 尝试在屏幕:55中打印您正在访问的arrays的大小,您应该看到问题。