簡體   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