我有一个带有播放器(是图像)和矩形的程序,我希望当播放器与矩形发生碰撞时,图像的大小会增加。
现在,我有以下代码:
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()
我尝试添加“ colliderect”条件,但是它不起作用:
player_rect.width += 1
player_rect.height += 1
感谢您的帮助!
答案 0 :(得分:1)
此行
player = pygame.transform.scale(pygame.image.load("player.png").convert_alpha(), (i, i))
正在使用变量i
,但未在代码中定义。我不确定在哪里定义,但这是您想要的关键。无论如何,我将尝试在没有此信息的情况下回答:
事情是,放大rect
不会做任何事情,因为rect只是坐标。您必须缩放实际图像,pygame.transform.scale
会做到这一点。
您可以将图像保留在单独的变量player_img
中:
player_img = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.scale(player_img, (i, i))
然后,当您想按不同比例缩放时,只需再次调用.scale()
:
double_size_player = pygame.transform.scale(player_img, (i*2, i*2))
这仍然使我们对您未定义的i
变量感到迷惑,但我认为您已经明白了要点。请记住,您必须从缩放后的图像中提取一个新的rect
,因为它会更大。