0

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.

3
  • 1
    Swing or AWT? I've done something like this in Swing using a JScrollPane (without scrollbars), and set the model's value. Commented Sep 10, 2011 at 3:59
  • Do you want the logic, or the Java portion that makes the Canvas calls? Commented Sep 10, 2011 at 4:14
  • 2
    Just so you know, there are a lot of helpful articles over at java-gaming.org when it comes to Java game making. Commented Sep 10, 2011 at 4:40

1 Answer 1

1

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 addListener method.
    • Indirectly meaning that your character class posts events to a global event bus, with which the listeners register to receive events of particular types.
  • 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!

Sign up to request clarification or add additional context in comments.

2 Comments

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?
I'm not that familiar with such things, but I can recommend taking a look at Killer Game Programming in Java for examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.