Arham Haq
Arham Haq

Reputation: 11

How do I blit an image onto a specific rect?

I'm a beginner in Pygame and I'm having trouble trying to blit an image onto specific rects.

obstacle_width = 70
obstacle_height = random.randint(150, 450)
obstacle_colour = (211, 253, 117)
obstacle_x_change = -4
obstacle_x = 500
obstacle_gap = 170


def display_obstacle(height):
    top = pygame.draw.rect(screen, obstacle_colour,
                     (obstacle_x, 0, obstacle_width, height))
    bottom_obstacle_height = 635 - height - obstacle_gap
    bottom = pygame.draw.rect(screen, obstacle_colour,
                     (obstacle_x, height + obstacle_gap, obstacle_width,
                      bottom_obstacle_height))

I want to blit an image inside both the top and the bottom rects. I know how to add an image onto Pygame, but I want the image to be inside the rects, instead of above/below them.

Any help would be greatly appreciated!

Upvotes: 1

Views: 192

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

See What is a good way to draw images using pygame?. Load the image with pygame.image.load()

obstacle_image = pygame.image.load("obstacle.png")

Get the bounding rectangle of the image. Create a pygame.Rect for the obstacle. Set the center of the bounding rectangle through the center of the obstacle rectangle and use it to blit the image on the screen:

obstacle_rect = pygame.Rect(obstacle_x, height + obstacle_gap, obstacle_width, bottom_obstacle_height)
image_rect = obstacle_image.get_rect(center = obstacle_rect.center)
screen.blit(obstacle_image, image_rect) 

Upvotes: 1

Related Questions