Java 相机实现



我正在尝试为游戏实现相机功能,以便基本上扩展玩家的比赛场地,目前水平。我以前只做过一次相机类,但我经常遇到的一个问题是相机的位置有效,但图形中的 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 + "tt" + (-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;
}
}

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

这是我的相机的样子:

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

相关内容

  • 没有找到相关文章