ioeric
ioeric

Reputation: 155

pygame:How to make the rect of an image transparent or the same color with backgroud?

I just started using pygame today, and got a little trouble. I rotated the car image, but it seemed that the rect area not suited to the image perfectly(as showed in the picture, the white area is larger than the image I rotated).

Can you make the rect area's color transparent or the same as background so that the image looks better?

Thanks

car image

Hello, This is my concerning code(from 'Rapid Game Development in Python' by Richard Jones):

class CarSprite(pygame.sprite.Sprite):
    MAX_FORWARD_SPEED = 10
    MAX_REVERSE_SPEED = 10
    ACCELERATION = 2
    TURN_SPEED = 5

    def __init__(self, image, position):
        pygame.sprite.Sprite.__init__(self)
        self.src_image = pygame.image.load(image)
        self.src_image = self.src_image.convert()
        self.position = position
        self.speed = self.direction = 0
        self.k_left = self.k_right = self.k_down = self.k_up = 0
        self.rect = self.src_image.get_rect()
        self.rect.center = position

    def update(self, deltat):
        # SIMULATION
        self.speed += (self.k_up + self.k_down)
        if self.speed > self.MAX_FORWARD_SPEED:
            self.speed = self.MAX_FORWARD_SPEED
        if self.speed <-self.MAX_REVERSE_SPEED:
            self.speed = -self.MAX_REVERSE_SPEED
        self.direction += (self.k_right + self.k_left)
        x, y = self.position
        rad = self.direction * math.pi / 180
        x += -self.speed*math.sin(rad)
        y += -self.speed*math.cos(rad)
        self.position = (x, y)
        self.image = pygame.transform.rotate(self.src_image, self.direction)
        self.rect = self.image.get_rect()
        self.rect.center = self.position

    def draw(self,screen):
        self.image.set_alpha(150)
        screen.blit(self.image, self.rect)

Upvotes: 0

Views: 1469

Answers (1)

ThisIsAQuestion
ThisIsAQuestion

Reputation: 1967

I can't see the image for some reason, but I think what you want is

Surface.set_colorkey(Color, flags=0)

If you enter in the color of the background, it (the background) will become transparent. Another cool thing is that if you set the colorkey before you rotate the car, the background will automatically become the color you set the colorkey to.

Just be careful. If you are importing the image from an external source, make sure you do image=image.convert() before setting colorkey.

Upvotes: 1

Related Questions