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 Answer
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)
1 Comment
mikera
Yep, give each object its own (x,y) co-ordinates relative to the world/background. draw them all after drawing the background. If you want certain objects to appear on top of other objects then draw them last (you can do this e.g. by sorting all the objects before you draw them)