java无法访问的代码错误(渲染class游戏开发)

java unreachable code error (Render class game development)

我一直在开发 java 游戏引擎,但我的渲染器一直收到无法访问的代码 error.The 错误出现在 setPixels 方法中。

public class Renderer {

    private int width, height;
    private byte[] pixels;


    public Renderer(GameContainer gc){
        width = gc.getWidth();
        height = gc.getHeight();
        pixels = ((DataBufferByte)gc.getWindow().getImage().getRaster().getDataBuffer()).getData();
    }

    public void setPixel(int x, int y, float a, float r, float g, float b){

        if((x < 0 || x>= width || y < 0 || y>= height) || a == 0){
            return;

            int index = (x + y * width) * 4;
            pixels[index] = (byte)((a * 255f) + 0.5f);
            pixels[index + 1] = (byte)((b * 255f) + 0.5f);
            pixels[index + 2] = (byte)((g * 255f) + 0.5f);
            pixels[index + 3] = (byte)((r * 255f) + 0.5f);

        }
    }

    public void clear(){
        for(int x = 0; x < width; x++){
            for(int y = 0; y < height; y++){
                setPixel(x,y,1,0,1,1);
            }
        }
    }

}

return语句结束了一个方法的执行。如果下面代码中的 if 语句是 运行,则该方法将命中 return 并在执行所有其他操作之前结束。您似乎不需要 setPixel 中的 return 语句,因为不需要过早地结束该方法。

public void setPixel(int x, int y, float a, float r, float g, float b) {
    if((x < 0 || x>= width || y < 0 || y>= height) || a == 0){
        //return;

        int index = (x + y * width) * 4;
        pixels[index] = (byte)((a * 255f) + 0.5f);
        pixels[index + 1] = (byte)((b * 255f) + 0.5f);
        pixels[index + 2] = (byte)((g * 255f) + 0.5f);
        pixels[index + 3] = (byte)((r * 255f) + 0.5f);

    }
}

我想这就是你想要做的?
您的 if 语句不应包含函数中的所有语句。

public void setPixel(int x, int y, float a, float r, float g, float b){

    // Check for invalid values
    if((x < 0 || x>= width || y < 0 || y>= height) || a == 0){
        // Break out of function if invalid values detected
        return;
    }

    // Update pixel
    int index = (x + y * width) * 4;
    pixels[index] = (byte)((a * 255f) + 0.5f);
    pixels[index + 1] = (byte)((b * 255f) + 0.5f);
    pixels[index + 2] = (byte)((g * 255f) + 0.5f);
    pixels[index + 3] = (byte)((r * 255f) + 0.5f);
}