Search code examples
javaswinggraphics2d

Drawing specific parts of Graphics2D


I have written a game, and now I would like to learn how to manipulate camera.

My drawing consists of this:

private void render()
{
    // CREATE THE GRAPHICS
    Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
    // MAKE THE PICTURE WHERE WE WILL PAINT EVERYTHING AT ONCE
    g.clearRect(0, 0, WIDTH, HEIGHT);
    // PAINT ANYTHING WE NEED HERE
    render(g);
    g.dispose();
    // SHOW THE WHOLE IMAGE RATHER THAN PAININT ONE OBJECT AT A TIME
    bufferStrategy.show();
}

My BufferStrategy is created like so:

    canvas = new Canvas();
    // once again I add 1 because java is stupid that's why
    canvas.setBounds(0, 0, WIDTH+1, HEIGHT+1);
    //canvas.setBounds(bounds);
    canvas.setIgnoreRepaint(true);

    // SET GRAPHICS DEVICE
    canvas.createBufferStrategy(2);
    bufferStrategy = canvas.getBufferStrategy();

In the render function I draw my game world with all the platforms where they should be. Now if the game world is bigger than the window size, and I would like to be able to focus on the character and draw the part of the world where character is, how would I do that? So let's say my window is 300 x 300, and my game world is 900 x 900, and my character is located in the middle so that I would like to display the part of the graphics where x is 150 y is 150 and the width and height is 300 x 300.

So how would I go about taking that Graphics2D and shifting it over by specified values? I am very sorry if this question has been answered or is easy, but I am new to this and really would like some help.

Thanks for any help in advance. I have tried all I know to no avail.


Solution

  • So how would I go about taking that Graphics2D and shifting it over by specified values?

    Why must you shift the Graphics2D? Why not create an image that extends beyond the viewport and simply shift the viewport. Then if the user gets close to the edge of the viewport, add an image to the leading edge and lop off a portion on the trailing edge.