如何让我的屏幕为我的瓷砖游戏渲染更大的瓷砖?

时间:2013-07-22 08:08:35

标签: java arrays indexoutofboundsexception

public void render(int xp, int yp, int tile, int colors, int bits) {
    xp -= xOffset;
    yp -= yOffset;
    boolean mirrorX = (bits & BIT_MIRROR_X) > 0;
    boolean mirrorY = (bits & BIT_MIRROR_Y) > 0;

    int xTile = tile % 32;
    int yTile = tile / 32;
    int toffs = xTile * 8 + yTile * 8 * sheet.width;

    for (int y = 0; y < 8; y++) {
        int ys = y;
        if (mirrorY) ys = 7 - y;
        if (y + yp < 0 || y + yp >= h) continue;
        for (int x = 0; x < 8; x++) {
            if (x + xp < 0 || x + xp >= w) continue;

            int xs = x;
            if (mirrorX) xs = 7 - x;
            int col = (colors >> (sheet.pixels[xs + ys * sheet.width + toffs] * 8)) & 255;
            if (col < 255) pixels[(x + xp) + (y + yp) * w] = col;
        }
    }
}

我按照youtube上的教程来创建该方法,但它只渲染了8x8的精灵片。我想让它渲染32x32的图块,但是当我把它改成所有的8s到32s时这样:

public void render(int xp, int yp, int tile, int colors, int bits) {
    xp -= xOffset;
    yp -= yOffset;
    boolean mirrorX = (bits & BIT_MIRROR_X) > 0;
    boolean mirrorY = (bits & BIT_MIRROR_Y) > 0;

    int xTile = tile % 32;
    int yTile = tile / 32;
    int toffs = xTile * 32 + yTile * 32 * sheet.width;

    for (int y = 0; y < 32; y++) {
        int ys = y;
        if (mirrorY) ys = 7 - y;
        if (y + yp < 0 || y + yp >= h) continue;
        for (int x = 0; x < 32; x++) {
            if (x + xp < 0 || x + xp >= w) continue;

            int xs = x;
            if (mirrorX) xs = 7 - x;
            int col = (colors >> (sheet.pixels[xs + ys * sheet.width + toffs] * 32)) & 255;
            if (col < 255) pixels[(x + xp) + (y + yp) * w] = col;
        }
    }
}

它给我一个错误说:

Exception in thread "Thread-3" java.lang.ArrayIndexOutOfBoundsException: -1184
    at orbis.src.Screen.render(Screen.java:79)
    at orbis.src.TileWater.render(TileWater.java:37)
    at orbis.src.World.renderBackground(World.java:143)
    at plixel.orbis.Orbis.render(Orbis.java:383)
    at plixel.orbis.Orbis.run(Orbis.java:297)
    at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:0)

由于我看不到整个代码,我无法确定,但假设line 79访问pixels数组,您可以访问elemnt out of bounds。

据推测,xs + ys * sheet.width + toffs(x + xp) + (y + yp) * w两个表达式中的一个变为大于数组pixels 负数(请参阅 Andrew Thompsons 评论

在旁注中,似乎if (mirrorY) ys = 7 - y;应该翻转y的增加,因此它应该是if (mirrorY) ys = 32 - 1 - y;(我猜)。翻转x坐标也是如此。我认为这是表达式否定的原因。

进一步说明:您可能必须更新数组边界: 例如:

int[] array = new int[10];
array[10];

这会产生一个越界错误,要么将数组的大小更改为11,要么改为访问array[9]


一般来说,最好使用常量,而不是在很多地方出现的硬编码大小,并且可能会发生变化。在java中,您可以使用public static final来声明常量。