RenderUpdates.draw() always returns rects

Question:

I’m using a sprite group class from pygame, specifically pygame.sprite.RenderUpdates

The reason I’m using that sprite group class is because it’s supposed to return a list of rects that have been modified.

Specifically, the documentation says this about pygame.sprite.RenderUpdates draw() method:

…This method also returns a list of Rectangular areas on the screen
that have been changed. The returned changes include areas of the
screen that have been affected by previous Group.clear() calls.

My issue

My issue is that the draw() method is returning a list of rects, even when I don’t move any sprites (when there is no animation at all).

Isn’t the draw() method only supposed to return rects that have been changed?

My minimal example is below:

    background_group = pygame.sprite.RenderUpdates()
    character_group = pygame.sprite.RenderUpdates()

    character_group.clear(screen, bg_surface)

    character_group.update()

    # The issue is below. 
    # I always get a list of rects, even if I don't call the update() method above.
    update_rects = background_group.draw(screen)
    update_rects += character_group.draw(screen)

    # I always have rects here (even when I don't move any sprites). Why?
    print(update_rects)

    pygame.display.update(update_rects)

    clock.tick(30)

Also, is this the correct way to get updated rects from 2 sprite groups?

update_rects = background_group.draw(screen)
update_rects += character_group.draw(screen)
Asked By: garlic

||

Answers:

Isn’t the draw() method only supposed to return rects that have been changed?

No it is not. pygame.sprite.RenderUpdates.draw. does not validate the content of the redraw areas or compare pixels, because that would cost too much time. The method collects only the areas that are redrawn, even if they are redrawn with the same content. This is because every Group.draw() causes Group.clear(). See the documentation of pygame.sprite.RenderUpdates.draw:

Draws all the Sprites to the surface, the same as Group.draw(). This method also returns a list of Rectangular areas on the screen that have been changed. The returned changes include areas of the screen that have been affected by previous Group.clear() calls.

You must care about that and avoid redrawing of objects that have not changed. One way I can think of is to put each sprite that has been moved and needs to be updated into an "update" group, and then draw only that group. In case of minimize/restore the entire scene must be redrawn, but in this case performance does not matter.

Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.