I'm creating my first game in Java. It is a simple 2D top-down shooter game. I want to have the camera follow my character around, so, using Canvas, how do I make it so the camera follows the character exactly in the center. While the map is moving when I hit the arrow keys.
1 Answer
One possibility for the logic is such:
- Create a listener and attach it to your character (either directly or indirectly depending on your design). Listen for character movement, or position changes.
- Directly meaning that your character class has an
addListenermethod. - Indirectly meaning that your character class posts events to a global event bus, with which the listeners register to receive events of particular types.
- Directly meaning that your character class has an
- Calculate the camera position based on the character position & center it accordingly. This will require a little math!
By implementing this using an event system you can easily separate the logic that centers the camera from the logic that moves the character. This way you can have the arrow keys move or you can use click to move and the camera logic will be unaffected.
Sorry I cannot provide general help regarding the actual Java 2D and Canvas calls that you might need to make, but I hope that a broad example of how one might go about doing this helps!
2 Comments
Anonymous
Thanks, this was a big help! I'm fairly new with Java game dev, so I was wondering how I actually make a "camera". Like how do I zoom/pan with the "camera"? I understand you have to size everything else accordingly, but can I have an example/step in the right direction?
Nate W.
I'm not that familiar with such things, but I can recommend taking a look at Killer Game Programming in Java for examples.
Canvascalls?