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)