Pygame how to fix 'trailing pixels'?

2020-01-24 10:10发布

问题:

In the image the red trail is a trail that pygame is creating when I have a bounding rectangle added around sprites. The sprite also does it and the simplest solution was to just clear the surface to black after each redraw. However attempting to do so on the entire main surface is not such a good idea. How can I fix this?

回答1:

Normally you will do:

def draw():
    # fill screen with solid color.
    # draw, and flip/update screen.

But, you can update just dirty portions of the screen. See pygame.display.update():

pygame.display.update()
Update portions of the screen for software displays
update(rectangle=None) -> None
update(rectangle_list) -> None

This function is like an optimized version of pygame.display.flip() for software displays. It allows only a portion of the screen to updated, instead of the entire area. If no argument is passed it updates the entire Surface area like pygame.display.flip().

You can pass the function a single rectangle, or a sequence of rectangles. It is more efficient to pass many rectangles at once than to call update multiple times with single or a partial list of rectangles. If passing a sequence of rectangles it is safe to include None values in the list, which will be skipped.

It's best to use it in combination with RenderUpdates, which is a Sprite.Group:

pygame.sprite.RenderUpdates
Group sub-class that tracks dirty updates.
RenderUpdates(*sprites) -> RenderUpdates
This class is derived from pygame.sprite.Group(). It has an extended draw() method that tracks the changed areas of the screen.



回答2:

Just have a black rectangle and blit that overtop of where your sprite was on the previous frame and that should get rid of it. Just remember to do this before you blit your sprite or your new sprite will be partly blacked out.



回答3:

Take the name of your screen. (For my case it's screen.) And do...

screen.fill((0, 0, 0))

Put that before the bliting and after the drawing. (It would make a black background.) Hope this helps!



回答4:

If you want to avoid redrawing the whole screen, then just fix the region that was "damaged" by your sprite. Already suggested is to draw a black rectangle over where your sprite was. That works if your background is always completely black. However, if there was a background image, then you can copy just the damaged part of the background image back to the screen.

If the background is more dynamic, then another solution is to copy the part of the screen that you will cover with a sprite before drawing that sprite, and store it somewhere. Then draw the sprite, and flip the screen if necessary. Right before moving the sprite, copy the saved part of the background back to the screen, and then repeat all this over again.



标签: pygame draw