问题描述
运行代码并按向左箭头时,太空飞船将重叠/相乘。我希望该对象停止复制。这是代码:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((288,512))
clock = pygame.time.Clock()
spaceship = pygame.image.load(r'C:\Users\Anonymous\Downloads\New folder\spaceship.png')
x = 150
y = 495
spaceship_rect = spaceship.get_rect(center=(x,y))
veLocity = 10
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > 0:
x -= veLocity
spaceship_rect = spaceship.get_rect(center=(x,y))
screen.blit(spaceship,spaceship_rect)
pygame.display.update()
clock.tick(120)
解决方法
在表面上绘制的任何对象都永久停留在该位置。绘制对象只会持续改变表面上某些像素的颜色。
在绘制场景并更新显示之前,您必须通过pygame.Surface.fill
清除所有帧中的显示:
screen.fill(0)
screen.blit(spaceship,spaceship_rect)
pygame.display.update()
完整示例:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((288,512))
clock = pygame.time.Clock()
spaceship = pygame.image.load(r'C:\Users\Anonymous\Downloads\New folder\spaceship.png')
x = 150
y = 495
spaceship_rect = spaceship.get_rect(center=(x,y))
velocity = 10
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
spaceship_rect = spaceship.get_rect(center=(x,y))
screen.fill(0)
screen.blit(spaceship,spaceship_rect)
pygame.display.update()
clock.tick(120)