Pygame Erasing Images on Backgrounds

后端 未结 3 891
北荒
北荒 2021-01-14 08:52

You blit an image onto your surface to use as your background. Then you press button X to blit an image on the same surface, how do you erase the image? I have this so far,

相关标签:
3条回答
  • 2021-01-14 09:06

    There are basically two things you can do here. You can go the simple route and just draw the background again...

    if event.key == pygame.K_BACKSPACE:
       screen.blit(background, (0,0))
    

    Or, if you want it to be a little more efficient, you can have the blit method only draw the part of the background that the player image is covering up. You can do that like this...

    screen.blit(background, (x, y), pygame.Rect(x, y, 62, 62))
    

    The Rect in the third argument will cause the blit to only draw the 62x62 pixel section of 'background' located at position x,y on the image.

    Of course this assumes that the player image is always inside the background. If the player image only partially overlaps the background I'm not entirely sure what will happen. It'll probably throw an exception, or it'll just wrap around to the other side of the image.

    Really the first option should be just fine if this is a fairly small project, but if you're concerned about performance for some reason try the second option.

    0 讨论(0)
  • 2021-01-14 09:12

    Normally the blit workflow is just to blit the original background to screen.

    In your code you would use screen.blit(background, (0,0))

    When you start combining lots of surfaces you will probably want either a variable or a list of variables to keep track of screen state.

    E.g.

    Initialise Background

    objectsonscreen = []
    objectsonscreen.append(background)
    screen.blit(background, (0,0))
    

    Add Sprite

    objectsonscreen.append(player)
    screen.blit(player, (x, y))
    

    Clear Sprite

    objectsonscreen = [background]
    screen.blit(background, (0,0))
    

    See here for more information on sprites in Pygame. Note that if your background isn't an image background and is just a solid color you could also use screen.fill([0, 0, 0]) instead.

    0 讨论(0)
  • 2021-01-14 09:14

    I personally use

    pygame.draw.rect(screen, (RgbColorHere), (x, y, width, height))
    
    0 讨论(0)
提交回复
热议问题