Java Camera Implementation

时间:2018-05-06 18:19:58

标签: java graphics graphics2d

我正在尝试为游戏实现一个摄像头功能,以便基本上横向扩展播放器的游戏区域。我之前只拍了一次相机课,但是我总是接触到的一个问题是相机的位置是否正常工作但是图形中的translate()没有做任何事情或玩家无法移动。我尝试了几种不同的解决方案和建议,但我无法弄清问题是什么。这是最基本的代码:

public class GamePanel extends JPanel implements ActionListener 
{       
    public GamePanel()
    {
        setBackground(Color.WHITE);
        setLayout(null);
        setOpaque(false);
        cell = new WBCell();
        addKeyListener(cell);
        camera = new Camera(cell);
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        grabFocus();
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.translate(camera.getX(), camera.getY()); 
        g2.drawImage(cell.getImage(), cell.getX(), cell.getY(), null);
        g.translate(-camera.getX(), -camera.getY());
    }

    public void actionPerformed(ActionEvent e) {
        Game.getCards().show(Game.getCardP(), "Start");
    }

相机将播放器保持在屏幕中央的基本代码:

public class Camera 
{
    private WBCell player;
    private int x = 0, y = 0;

    public Camera(WBCell wCell)
    {
        player = wCell;
    }

    public void cameraMove()
    {
        System.out.println("Cam: " + x + ", " + y + "\t\t" + (-player.getX() + Game.WIDTH/2) + ", " + (-player.getY() + Game.HEIGHT/2));
        x = -player.getX() + Game.WIDTH/2;
        y = -player.getY() + Game.HEIGHT/2;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }
}

作为参考,一旦调用了drawImage(),单元格对象或WBCell类只会加载一个BufferedImage并在面板上将其拍打。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

这就是我的相机的样子:

x = (player.getX()+(player.getWidth()/2)) -           game.getWidth()/2;
y = (player.getY()+(player.getHeight()/2)) - game.getHeight()/2;

g2d.translate(-camX, -camY);
 //render everything(including player)
g2d.translate(camX, camY);