I am developing a 2D Metroidvania which consists of a series of interconnected levels. When my player gets near a portal which can take him to a new map, I want to pre-load the next map so that there is a seamless transition when he actually enters the portal.
Here is some background about the structure of my code.
Each level is represented by a Tiled TMX file in which I have specified where various objects of different sprite classes spawn (for example, enemies, pickups, levers, etc.). When starting a new game, loading a saved game, or changing a level, my game loop runs through the appropriate TMX file and generates all the objects in that level.
For example, here is a simplified version of my
level = "level_1.tmx"
Globals.scene = "game"
# create groups
self.all_sprites = pg.sprite.Group()
self.walls = pg.sprite.Group()
# load map and spawn objects
self.map = TiledMap(path.join(self.map_folder, level))
self.map_name = level
self.map_img = self.map.make_map()
self.map_rect = self.map_img.get_rect()
# spawn objects
for tile_object in self.map.objects:
if tile_object.name == 'player':
Player(self, tile_object.x, tile_object.y)
if tile_object.name == 'wall':
Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height)
I handle level changes like this: If the
Player object intersects a
Portal object, a
change_map() method is called which loads a new map (the one associated with the intersected portal) and positions the player at the appropriate position on the new map. The
change_map() method looks very similar to the
new_game() method above, except that it empties all the sprite groups and hangs on to the player object for repositioning on the new map.
I want to restructure my code so that when the player gets near a portal object (say, within 640 pixels), the map associated with the portal begins to load. This way, when the player enters the portal, the map will load instantly.
I was thinking that I could check to see if the player is near a portal in my game's
update() method. If he is, I could call a
preload_map() method. But I am unsure how this function should look and how to transition to the new map when the player enters the portal. In order to avoid a stutter when the new map loads, do I need to learn about multiple threads? Maybe I should simply load all the new map images and sprites into their own variables (suffix them with "temp" or something) and then, when my player enters the portal, I can effectuate transition with lines like
self.map_img = self.map_img_temp and
self.all_sprites = self.all_sprites_temp.
So my question is: Given the structure of my code, how can I use pre-loading to achieve seamless map transitions?
Here is a similar question where the poster does not specify enough information about the structure of their code.