Djanito
Djanito

Reputation: 197

Increase the size of an image during a collision with pygame?

I have a program with a player (who is an image) and a rectangle and I want that when the player has a collision with the rectangle, the size of the image increase.


For now, I have this code :

import pygame
from random import randint

WIDTH, HEIGHT = 800, 800
FPS = 60

pygame.init()

win = pygame.display.set_mode((WIDTH, HEIGHT))
fenetre_rect = pygame.Rect(0, 0, WIDTH, HEIGHT)
pygame.display.set_caption("Hagar.io")
clock = pygame.time.Clock()

bg = pygame.image.load("bg.png").convert()
bg_surface = bg.get_rect(center=(WIDTH / 2, HEIGHT / 2))
bg_x = bg_surface.x
bg_y = bg_surface.y
x_max = WIDTH / 2
y_max = HEIGHT / 2

# player
player = pygame.transform.scale(pygame.image.load("player.png").convert_alpha(), (i, i))
player_rect = player.get_rect(center=(x_max, y_max))

# cell
rect_surface = pygame.Rect(300, 500, 20, 20)

# Game loop
running = True
while running:
    dt = clock.tick(FPS) / 1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if player_rect.colliderect(rect_surface):
        print("collide")

    bg_surface.x = bg_x
    bg_surface.y = bg_y

    # draw on screen
    win.blit(bg, bg_surface)
    pygame.draw.rect(win, (255, 0, 0), rect_surface)
    win.blit(player, player_rect)
    pygame.display.flip()

pygame.quit()

I have try to add in the "colliderect" condition but it does not work :

player_rect.width += 1
player_rect.height += 1

Thanks for your help !

Upvotes: 0

Views: 720

Answers (1)

nosklo
nosklo

Reputation: 222792

This line

player = pygame.transform.scale(pygame.image.load("player.png").convert_alpha(), (i, i))

is using the variable i but it is not defined in your code. I'm not sure where it is defined, but it is key to what you want. I will try to answer without this information anyway:

Thing is, enlarging the rect won't do anything, because a rect is just coordinates. You have to scale the actual image, and pygame.transform.scale does exactly that.

You can keep the image in a separate variable player_img:

player_img = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.scale(player_img, (i, i))

Then when you want to scale it differently, just call .scale() again:

double_size_player = pygame.transform.scale(player_img, (i*2, i*2))

That still leaves us to the mistery of your undefined i variable, but I think you get the gist of it. Remeber that you have to extract a new rect from the scaled image because it will be bigger.

Upvotes: 2

Related Questions