微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何阻止对象在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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。