0

Question regarding pygame's "draw" method. If I had a sprite group named "spritegroup" and had a display surface named "screen" I could use spritegroup.draw(screen) to draw the spritegroup onto the screen. Additionally, assume the sprite has an update method which makes the current x position of the sprite change by 5 units. This update method will be called in the main game loop upon the user hitting a specific key.

To explain further, we would call the update method in the game loop every time the key was hit. Then, we would draw the spritegroup(which now has an altered position) to the screen. Then, we can use the flip method to update these changes to the user's monitor.

However, considering the process described above is within a loop, the next time the user hits the key, the update method will be called and once again the sprite group will once again be drawn onto the screen. My confusion is at this point: in the previous iteration we have already drawn the sprite group onto the screen. Yet, we are doing so again(albeit in an altered position), in this iteration. Why wouldn't this result in two sprite groups being displayed to the user when the pygame.display.flip() method is called?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

The answer is, in the example above it does end up drawing the spritegroup to the screen at every iteration. Basically, the screen is like a canvas with multiple layers on it I guess: the previous layers never get cleared. As a result, if you draw a spritegroup at pos x and then in the next iteration draw it at pos x + 10, the spritegroup will be shown at both positions.

To get around this, reblit the background to the screen every iteration. This, essentially takes the screen(which I analogize as being like a canvas) and plasters the background on top of everything that was on the screen before. Esentially, you are giving yourself a clean slate by covering up the previous drawings with your background image. Upon doing this, you may then draw the updated spritegroup ontop of the new background.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • *"Basically, the screen is like a canvas with multiple layers "* - No. The display has only 1 layer and you always draw on the same layer. You must clear the display in each frame. – Rabbid76 May 09 '22 at 05:43