pythonpygamepytmx

Need help on performing Frustum Culling on my platform game


What I m trying to do in order to implement the Frustum Culling algorithm is to start the nested for loop in the render() function from a position that will depend on the player x and y position, such that the code will only loop through a small portion of the .tmx file the portion that has to render. Now the question is, How do I start the loop from a position that will depend from my Player coordinates? Thanks in advance for the help.

import pygame
import pytmx
pygame.init()

class Map():
    def __init__(self,filename):
        tm=pytmx.load_pygame(filename,pixelalpha=True)
        self.width=tm.width * tm.tilewidth
        self.height=tm.height*tm.tileheight
        self.tmxdata=tm

    def render(self,surface):
        ti=self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer,pytmx.TiledTileLayer):
                for x,y,gid in layer:
                    tile = ti(gid)
                    if tile
                        surface.blit(tile,(x*self.tmxdata.tilewidth,y*self.tmxdata.tileheight))
    def make_map(self):
        temp_surface=pygame.Surface((self.width,self.height))
        self.render(temp_surface)
        return temp_surface

Solution

  • You can calculate the current tilemap coordinate at a point in the world if the tilemap sizes are constant (i.e every tile has the same width and height).

    Say that we have tiles that are 20 pixels wide and 20 pixels high, and your player is at position (432, 36). Then we can find which tile he/she is at by doing integer division (divide and truncate/"remove the decimals").

    tile_x = player_x // tile_width
    tile_y = player_y // tile_height
    

    In our case, the player will stand on the tile 21 on the x-axis (432 // 20 = 21), and tile 1 on the y-axis (36 // 20 = 1).

    From there you can define how big of an area around the player you want to be visible. If you want to render 1 tile in each direction (including the one the player is standing on), you'll have to iterate through x = 20 to 22 and y = 0 to 2.