2

我正在用java制作一个基于瓷砖的平台游戏。我渲染了一个存储在二维数组中的地图,但是当这个数组非常大时,我的游戏开始变慢。我意识到我必须只渲染地图的可见部分,我尝试这样做,但我编写了非常糟糕的代码,只能部分工作,所以我删除了它。我怎样才能正确地做到这一点?这是我的代码(没有 hacky 的东西)。另外我怎么能使用System.nanoTime()而不是System.currentTimeMillis()

package sexy_robot_from_another_dimension;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game extends JPanel
{
    int playerX = 50;
    int playerY = 50;
    static boolean up = false;
    static boolean down = false;
    static boolean right = false;
    static boolean left = false;
    int playerSpeed = 1;
    String[][] map;
    int blockSize = 20;
    int jumpLoop = 0;
    int maxJumpLoop = 280;
    static BufferedImage block, player;
    int playerWidth = 20;
    int playerHeight = 35;
    int cameraX = 0; 
    int cameraY = 0;
    long nextSecond = System.currentTimeMillis() + 1000;
    int frameInLastSecond = 0;
    int framesInCurrentSecond = 0;

    public Game()
    {
        super();
        try 
        {
            map = load("/maps/map1.txt");
        } 

        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Timer timer = new Timer();
        TimerTask task = new TimerTask() 
        {
            @Override
            public void run() 
            {

                if(up)
                {               
                    if((!playerIsOnBlock(playerX, playerY).equals("0")) || (!playerIsOnBlock(playerX + (playerWidth - 1), playerY).equals("0")))
                    {
                        timeToJump();
                    }
                }

                if(down)
                {               
                }

                if(right)
                {
                    if((playerIsLeftBlock(playerX, playerY).equals("0")) && (playerIsLeftBlock(playerX, playerY + (playerHeight/2 - 1)).equals("0")) && (playerIsLeftBlock(playerX, playerY + (playerHeight - 1)).equals("0")))
                    {
                        playerX += playerSpeed;
                    }
                }

                if(left)
                {                   
                    if((playerIsRightBlock(playerX, playerY).equals("0")) && (playerIsRightBlock(playerX, playerY + (playerHeight/2 - 1)).equals("0")) && (playerIsRightBlock(playerX, playerY + (playerHeight - 1)).equals("0")))
                    {
                        playerX -= playerSpeed;
                    }
                }

                repaint();
            }
        };
        timer.scheduleAtFixedRate(task, 0, 10);

        Timer timerGrav = new Timer();
        TimerTask taskGrav = new TimerTask() 
        {
            @Override
            public void run() 
            {
                if((playerIsOnBlock(playerX, playerY).equals("0")) && (playerIsOnBlock(playerX + (playerWidth - 1), playerY).equals("0")))
                {
                    playerY += playerSpeed;
                    repaint();
                }
            }
        };
        timerGrav.scheduleAtFixedRate(taskGrav, 0, 6);
    }

    void timeToJump()
    {
        if(jumpLoop == 0)
        {
            jumpLoop = 1;
            Timer timer = new Timer();
            TimerTask task = new TimerTask() 
            {
                @Override
                public void run() 
                {
                    if((playerIsBelowBlock(playerX, playerY).equals("0")) && (playerIsBelowBlock(playerX + (playerWidth - 1), playerY).equals("0")))
                    {               
                        playerY -= playerSpeed;
                        jumpLoop++;
                        repaint();
                    }

                    else
                    {
                        jumpLoop = maxJumpLoop;
                    }

                    if(jumpLoop == maxJumpLoop)
                    {
                        jumpLoop = 0;
                        cancel();
                    }
                }
            };
            timer.scheduleAtFixedRate(task, 0, 3);
        }
    }

    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        long currentTime = System.currentTimeMillis();
        if (currentTime > nextSecond) 
        {
            nextSecond += 1000;
            frameInLastSecond = framesInCurrentSecond;
            framesInCurrentSecond = 0;
        }
        framesInCurrentSecond++;

        g.drawString(frameInLastSecond + " fps", 10, 20);
        cameraX = -playerX + getWidth()/2;
        cameraY = -playerY + getHeight()/2;
        g.translate(cameraX, cameraY);
        for (int x = 0; x < map.length; x++) 
        {
            for (int y = 0; y < map[0].length; y++) 
            {
                switch(map[x][y])
                {
                case "0":
                    break;
                case "1":
                    if(block != null)
                    {
                        TexturePaint tp0 = new TexturePaint(block, new Rectangle(0, 0, blockSize, blockSize));
                        g2.setPaint(tp0);
                    }
                    g.fillRect(y*blockSize, x*blockSize, 20, 20);
                    break;
                }
            }
        }
        g.setColor(Color.BLACK);
        if(player != null)
        {
            TexturePaint tp0 = new TexturePaint(player, new Rectangle(playerX, playerY, playerWidth, playerHeight));
            g2.setPaint(tp0);
        }
        g.fillRect(playerX, playerY, playerWidth, playerHeight);
        g.setColor(Color.black);
        g.setFont(new Font("Droid Sans Mono", Font.PLAIN, 12));
        g.drawString("Sexy!", playerX - 5, playerY - 10);
    }

    boolean outOfMap(int x, int y)
    {
        y -= blockSize - 1;
        x -= blockSize - 1;
        if((y/blockSize <= map.length - 2) && (y/blockSize >= 0) && (x/blockSize <= map[0].length-2) && (x/blockSize >= 0))
        {
            return false;
        }
        return true;
    }

    String playerIsOnBlock(int x, int y)
    {
        y += playerHeight;
        if(!outOfMap(x, y))
        {
            if(map[y/blockSize][x/blockSize] != "0")
            {
                return map[y/blockSize][x/blockSize];
            }
        }
        return "0";     
    }

    String playerIsBelowBlock(int x, int y)
    {
        y -= playerSpeed;
        if(!outOfMap(x, y))
        {
            if(map[y/blockSize][x/blockSize] != "0")
            {
                return map[y/blockSize][x/blockSize];
            }
        }
        return "0";     
    }

    String playerIsLeftBlock(int x, int y)
    {
        x += playerWidth;
        if(!outOfMap(x, y))
        {
            if(map[y/blockSize][x/blockSize] != "0")
            {
                return map[y/blockSize][x/blockSize];
            }
        }
        return "0";     
    }

    String playerIsRightBlock(int x, int y)
    {
        x -= playerSpeed;
        if(!outOfMap(x, y))
        {
            if(map[y/blockSize][x/blockSize] != "0")
            {
                return map[y/blockSize][x/blockSize];
            }
        }
        return "0";     
    }


    String[][] load(String file) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
        int lines = 1;
        int length = br.readLine().split(" ").length;
        while (br.readLine() != null) lines++;
        br.close();
        br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
        String[][] map = new String[lines][length];
        for (int i = 0; i < lines; i++)
        {
            String line = br.readLine();
            String[] parts = line.split(" ");
            for (int y = 0; y < length; y++)
            {
                map[i][y] = parts[y];
            }
        }
        br.close();
        return map;
    }
}

谢谢!

4

2 回答 2

5

看来您的相机以播放器为中心,那么有两种方法可以做到这一点,我喜欢第一种方法,它更干净一点:

第 1 步:创建一个限定相机视图的矩形,并检查地图 x,y 是否在此视图内,仅在为真时渲染。

  Rectangle cameraView = new Rectangle(playerX - getWidth() / 2, playerY - getHeight() / 2, getWidth(), getHeight());
    for (int x = 0; x < map.length; x++) {
        for (int y = 0; y < map[0].length; y++) {
            if (!cameraView.contains(x*blockSize, y*blockSize))
                continue;
            switch (map[x][y]) {
            case "0":
                break;
            case "1":
                if (block != null) {
                    TexturePaint tp0 = new TexturePaint(block, new Rectangle(0, 0, blockSize, blockSize));
                    g2.setPaint(tp0);
                }
                g.fillRect(y * blockSize, x * blockSize, 20, 20);
                break;
            }
        }
    }

(playerX,playerY)第二个选项是简单地计算到每个屏幕中心的距离map[x][y]并跳过所有map[x][y]超出您的查看范围的距离,这对代码来说有点难看,我真的不推荐这个,上面的矩形选项应该很快足够的。

编辑: @JasonC 是的,我没有考虑例如当 x 值肯定在视图之外时,它仍然会通过所有 y 值进入 y 循环。可以简单地在 x 循环中创建一个虚拟变量并进行以下检查

for (int x = 0; x < map.length; x++) {
  int dummyY = playerY
  if(!cameraView.contains(x,dummyY))
    continue;
    ....
   //rest of code ommitted

您可以做的另一个优化是考虑不设置TexturePaint(昂贵的操作),而是简单地绘制块的图像:

g.fillRect(y * blockSize, x * blockSize, 20, 20);

替换为

g.drawImage(block, y*blockSize, x*blockSize, null);

与播放器图像相同。

于 2013-08-07T17:01:49.687 回答
4

使用 Graphics.setClip() 将剪辑区域设置为可见区域,这将阻止大多数渲染操作在该区域之外生效。

对于这还不够的绘图操作(也许您还想避免对剪切区域之外的对象进行计算或其他操作),测试您的对象边界与剪切矩形的边界,如果它不相交则跳过该对象。

请参阅Graphics.setClip()

例如,可以通过计算地图上绝对超出可见区域的块范围,并将其从 for 循环中排除(如果您知道它们在剪切区域之外,则没有意义对剪切区域进行测试块)已经)。获取剪切区域,将其转换为地图索引坐标,然后您将知道地图中可见区域的位置,并且您可以迭代地图的该子部分。

于 2013-08-07T16:38:26.927 回答