I have a basic game, in which the player moves the environment around the screen, to give the gamer an impression that the player is actually moving. I want this game to be large and have an open world, each piece of scenery is an object and each frame it updates the scenery to make itself move relative to the player. The trouble is with large amounts of objects this causes the game to slow down, but the objects HAVE to be updated otherwise they will become out of synch with the player. So how can I increase the performance of my game without splitting it up into tiny little levels?
Its a 2D top down game. The position of each object is updated each time, but when there are a large number of objects this takes a long time.
Answer
The technique you're describing is called Scrolling.
Some suggestions:
- Do not update the position of each object relative to the player (or the viewport). Instead, have your rendering calculate the screen position of each object before it renders it (e.g. subtract the current viewport position). This is known as mapping WORLD coordinates to VIEW coordinates (you might do something else, such as rotation / scaling as well, if the view can rotate or scale)
- The technique to avoid rendering objects which are off the screen is known as "Culling". A simple way of doing it, is to perform the transformation to view-coordinates (as above), and if the object is clearly entirely outside the displayed area, it does not need to be drawn.
- Say you have a world with 1M objects in it. Probably, it will take too long (each frame) to scan all 1M objects, to determine which ones are outside the view (almost all of them). Therefore you need to use some optimisation. The easiest way to do this, is to attach the objects to lists on a uniform grid, and only check the objects on the lists close to the viewport.
- If your objects are not axis-aligned boxes, then you can calculate Axis-Aligned Bounding Boxes (AABBs) for them, which makes culling (and other things, such as collision detection) easier.
- Another idea would be "lazy initialisation" of your world - only actually create parts of the world which are close to the player: split the world into "zones" or "blocks", and initialise the blocks as the player gets close to them. When the player is far away from a "zone" or "block", you can destroy it. This would save memory and mean that the world can be effectively infinite.
No comments:
Post a Comment