Krishnanshu Gupta
Krishnanshu Gupta

Reputation: 174

Java Camera Implementation

I'm trying to implement a camera feature for a game, in order to basically extend the playing field for the player, horizontally for now. I have only made a camera class once before, but a problem I always come in contact with is either the camera's positions work but translate() in Graphics doesn't do anything or the player is unable to move. I've tried several different solutions and suggestions, but am unable to figure out what the problem is. Here is the most basic code:

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

Basic code for the camera to keep the player in the center of the screen:

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

For reference the cell object or WBCell class just loads a BufferedImage and slaps it on the panel once drawImage() is called. Any suggestions would be greatly appreciated!

Upvotes: 0

Views: 382

Answers (1)

Maxwell
Maxwell

Reputation: 39

This is what my camera looks like:

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

Upvotes: 1

Related Questions