繁体   English   中英

如何阻止对象在 pygame 中重叠?

[英]How to stop objects from overlapping in pygame?

当我运行我的代码并按下向左箭头时,宇宙飞船正在重叠/相乘。 我希望对象停止复制。 这是代码:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM