【问题标题】:Check if Rendering Off Screen?检查是否渲染关闭屏幕?
【发布时间】:2014-08-16 02:27:00
【问题描述】:

最近,我一直在尝试改善游戏中的一些延迟问题,我这样做的一种方法是删除任何不必要的渲染。

这是我的TileMap 类中的render() 方法,它处理创建、更新和渲染游戏地图。

public void render(Graphics2D g) {

    for(int row = 0; row < numRows; row++) {

        for(int col = 0; col < numCols; col++) {

            if(map[row][col] == 0) continue;

            int rc = map[row][col];
            int r = rc / numTilesAcross;
            int c = rc % numTilesAcross;

            g.drawImage(tiles[r][c].getImage(), x + (col * tileSize) - 8, y + (row * tileSize) - 8, null);

        }

    }

}

我一直在尝试这样的事情:

if(x + (col * tileSize) - 8 < x + (col * tileSize) - 8 + Panel.WIDTH) continue;

Panel.WIDTH 是窗口的宽度。我不太确定需要什么算法来测试越界渲染。

检查图块是否在屏幕左侧,但这不起作用。

我还认为循环遍历所有行和列可能会很慢,我想对其进行更改,使其仅循环可在屏幕上呈现的图块数量。

【问题讨论】:

    标签: java render lag


    【解决方案1】:

    创建一些临时变量将有助于使其更易于理解:

    int pixelX = x + (col * tileSize) - 8;
    int pixelY = y + (row * tileSize) - 8;
    

    使用这些,您建议的检查等效于:

    if(pixelX < pixelX + Panel.WIDTH) continue;
    

    这显然不会跳过任何内容。

    你想要这样的东西:

    if(pixelX + tilesize <= 0) continue; // tile is off left side of screen
    if(pixelY + tilesize <= 0) continue; // tile is off top of screen
    if(pixelX >= Panel.WIDTH) continue; // tile is off right side of screen
    if(pixelY >= Panel.HEIGHT) continue; // tile is off bottom of screen
    

    假设Panel.WIDTHPanel.HEIGHT 是您正在绘制的对象的宽度和高度。这是对轴对齐边界框的碰撞检查,以防您需要搜索名称。

    这仍然不是最有效的方法 - 您最终会遍历整个地图,但随后会忽略大部分图块。更有效的方法是计算地图中你能看到的部分,然后绘制这些图块:

    // assuming x <= 8 and y <= 8
    int firstCol = ((8-x) / tileSize);
    int firstRow = ((8-y) / tileSize);
    int lastCol = firstCol + ((Panel.WIDTH + tileSize - 1) / tileSize); // Panel.WIDTH/tileSize, but rounding up
    int lastRow = firstRow + ((Panel.HEIGHT + tileSize - 1) / tileSize);
    
    for(int row = lastRow; row <= firstRow; row++) {
        for(int col = lastCol; col <= firstCol; col++) {
            // drawing code goes here
            // there's no need to test the tile is onscreen inside the loop
        }
    }
    

    【讨论】:

    • 您添加的最后一个方法对我不起作用,但您检查pixelX + tileSize &lt; 0pixelX &gt;= Panel.WIDTH 的第一个方法有效!我从大约 50 FPS 到大约 110 FPS。谢谢!
    • @sparklyllama 也许我在最后一个数学中犯了一个错误。不过总体思路是有效的 - 如果您可以计算要绘制哪些图块,那么它比单独检查每个图块要快。
    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    相关资源
    最近更新 更多