1

I am trying to make sprites appear as images in my pygame code. Here is one of the sprites:

class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.surf = pygame.Surface((20, 10))
        self.surf = pygame.image.load("Rocket 1.png").convert()
        self.rect = self.surf.get_rect(
            center=(
                random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
                random.randint(0, SCREEN_HEIGHT),
            )
        )
        self.speed = random.randint(5, 10)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            global score
            score += 1
            self.kill()

It works, but the image displays with a black background. Here is the image: missile As you can see, the image has no background, but when I run my code, it still displays it as having a black background.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [How to make a surface with a transparent background in pygame](https://stackoverflow.com/questions/328061/how-to-make-a-surface-with-a-transparent-background-in-pygame) – mkrieger1 Oct 06 '20 at 22:41
  • It only tells how to make a surface with a transparent background in that question. I am trying to make one with an image. –  Oct 06 '20 at 22:44
  • Yes, transparent instead of black. Is that not what you need? Did you try it? – mkrieger1 Oct 06 '20 at 22:45
  • You overwrite `self.surf` again after creating the `pygame.Surface((20, 10))` instance, by the way. This might be another problem. – mkrieger1 Oct 06 '20 at 22:47
  • What problem would it cause? –  Oct 06 '20 at 22:51
  • 1
    Did you also check these? [1](https://stackoverflow.com/questions/1634208/how-do-i-blit-a-png-with-some-transparency-onto-a-surface-in-pygame), [2](https://stackoverflow.com/questions/39932138/make-the-background-of-an-image-transparant-in-pygame-with-convert-alpha), [3](https://stackoverflow.com/questions/28645597/how-to-draw-a-transparent-image-in-pygame) – mkrieger1 Oct 06 '20 at 22:51
  • That the first line is not doing what you think because it gets overwritten. I don't know, I just noticed it. – mkrieger1 Oct 06 '20 at 22:51
  • This line? `class Enemy(pygame.sprite.Sprite):` –  Oct 06 '20 at 22:55
  • 1
    No, `self.surf = pygame.Surface((20, 10))`, because in the line below you set `self.surf` to something else. – mkrieger1 Oct 06 '20 at 22:56
  • If I deleted that line, would it still work? –  Oct 06 '20 at 22:57
  • You can answer that better than I can by just trying it. – mkrieger1 Oct 06 '20 at 22:58

1 Answers1

1

I used the 1st link given by @mkrieger1 and found out that .convert_alpha works. Thanks!