Currently I'm developing a RTS game using Python/PyGame and I got some problems with fps drops when there are many units on the screen.
Using Snakeviz profiling I found out that the function
update_vision() takes up a big majority of the processing.
This is because the function is checking every tile inside a radius of each unit (depending on the units defined vision range). When there are many units there are a lot of calculations that need to happen.
I'd like to optimize this somehow. Currently it's checking the same tiles over and over if the units vision ranges are overlapping. However I'm not sure how to go about this and would appreciate any help!
#-----Update vision & explored matrixes----- def update_vision(self): for i, group in enumerate(all_p_unit_sprite_list): if i+1 != self.player: continue for unit in group: rel_x, rel_y = unit.get_coord() for row in range(-unit.vision_range, unit.vision_range + 1): for col in range(-unit.vision_range, unit.vision_range + 1): loc_x = rel_x + row loc_y = rel_y + col if 0 <= loc_x < matrix_width and 0 <= loc_y < matrix_height: if abs(row) + abs(col) <= unit.vision_range: map_vision_matrix[loc_y][loc_x] = 1 map_explored_matrix[loc_y][loc_x] = 1
#-----Get grid coordinates----- def get_coord(self): col = self.rect.centerx // tile_size row = self.rect.centery // tile_size return (col, row)