Java(摆动)只绘制屏幕上可见的内容



我正在用java制作一个基于tile的平台游戏。我渲染了一个存储在二维数组中的地图,但当这个数组很大时,我的游戏开始变得缓慢。我意识到我只需要渲染地图中可见的部分,我试着这样做,但我写了一些非常糟糕的代码,只起了部分作用,所以我把它删除了。我该如何正确地做到这一点?这是我的代码(没有那些烦人的东西)。此外,我如何使用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;
    }
}

谢谢!

看起来你的相机是以玩家为中心的,然后有两种方法可以做到这一点,我喜欢第一种方法,它有点干净:

第1步:创建一个矩形来限制相机视图,并检查贴图x、y是否在此视图内,仅当为true时渲染。

  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;
            }
        }
    }

第二个选项是简单地计算每个map[x][y]到屏幕中心(playerX,playerY)的距离,并跳过所有超出您查看范围的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);

玩家图像也是如此。

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

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

请参阅Graphics.setClip().

例如,可以通过计算地图上肯定在可见区域之外的块的范围,并将其从for循环中排除来进行进一步的优化(如果知道块已经在外部,则没有针对剪切区域的意义测试块)。取裁剪区域,将其转换为地图索引坐标,然后您就会知道可见区域在地图中的位置,您只需迭代地图的该部分即可。

最新更新