Follow player

Hi,

Again a question from me. Ive made a level from 2500*2500. But now I have a problem, Ive searched at google but didnt found a good explain. How can I make that the camera is following the player? (I dont want moving the whole level)

Thank you in advance!

N1els5

By not wanting to move the whole level - what do you mean?

You’re going to have to draw things at different places. Easiest is probably to just draw everything at an offset and have the offset determined either by the player or another camera object that solely exist to follow the player around.

public void render(Graphics g, int hoff, int voff) {
   g.drawImage(sprite, x - hoff, y - voff);
}

Then by changing the hoff and voff values you can have the whole map shift in whatever direction you place. To follow player for example.

A good example what I want is the same as a mario level. But I dont want move the whole level only the player and the camera.

The map won’t move anywhere - it’s just getting drawn at a different place in reference to the visible screen area.

Ok, and whats the best option to do this? Somebody on google say with JPanels?

Play with the map’s offsets, since you dont draw all visual to one window.

I don’t get why you would use JPanels, unless your map was in a JPanel but the player wasn’t…and that’s bad design anways…

Use the translate method in Graphics2D

g.translate(x, y)

whenever you increase X of the player, you’ll want to decrease the x of whatever variable you use in the translate method, the same goes for Y