Java Scrolling Background

2019-05-29 05:20发布

问题:

How would you scroll the background in Java, to make it look like a sprite is moving? I am using an Applet. Is there a more efficient way than making all the objects in the game move left or right?

回答1:

Most games redraw the entire background every frame, then redraw all sprites on top of it.

If your background is just a big image, then this is surprisingly efficient (since a memory-> memory image copy is very fast).

To maintain the perception of scrolling in a 2D game:

  • Define a pair of coordinates (scrollX, scrollY) that store the current scroll position of the top left of the screen.
  • You can update scrollX and ScrollY whenever you want to scroll (e.g. following the player)
  • Give each sprite a co-ordinate (spriteX, spriteY) that is relative to the game world (i.e. the game background) and not relative to the screen position. Then you don't need to change these numbers when you scroll....
  • Then you need to draw the background at screen position (-scrollX, -scrollY) and each sprite at (spriteX-scrollX, spriteY-scrollY).
  • Java should take care of the screen clipping for you. But if your game world and background is large, then you may need some additional techniques to avoid the overhead of trying to draw offscreen objects (this would be called "view frustrum culling" in game development lingo)


标签: java scroll