首页 > 解决方案 > 在 Pygame 中删除对象?

问题描述

大家好,我只是想做一些很酷的事情,但我不知道如何在 pygame 中删除绘制的 OBJ 我在使用 remove() 和 Delete() 时出错

这是代码:

import pygame
pygame.init()
VEL = 5
SCREEN = pygame.display.set_mode((800,600))
pygame.display.set_caption("The test")
Clock = pygame.time.Clock()
Rect = pygame.Rect(500,300,30,30)
Rect1= pygame.Rect(300,300,30,30)
Run = True
     
def Collide() :
    if Rect1.colliderect(Rect):
        Rect.delete()   


while Run :
    Clock.tick(60)
    for  event in pygame.event.get():
        if event.type == pygame.QUIT:
            Run = False


    SCREEN.fill((83,83,83))        
    P1 = pygame.draw.rect(SCREEN,(0,255,0),Rect)
    P2 = pygame.draw.rect(SCREEN,(255,0,0),Rect1)

   
    KEY_PRESSED = pygame.key.get_pressed()
    if KEY_PRESSED[pygame.K_RIGHT] and Rect.x+VEL+ Rect.height<800:
        Rect.x +=VEL
    if KEY_PRESSED[pygame.K_LEFT]  and Rect.x-VEL>0:
        Rect.x -=VEL        
    if KEY_PRESSED[pygame.K_UP] and Rect.y-VEL>0:
        Rect.y -=VEL  
    if KEY_PRESSED[pygame.K_DOWN] and Rect.y+VEL+ Rect.height<600:
        Rect.y +=VEL                
    Collide()

    pygame.display.flip()
pygame.quit()

等待一些答案。

标签: pythonpygamecollision

解决方案


您不能“删除”分别在 Surface 屏幕上绘制的内容。Surface 仅包含按行和列组织的一堆像素。如果你想“删除”一个对象,那么你一定不能绘制它。

例如:

def Collide():
    global collided
    if Rect1.colliderect(Rect):
        collided = True   

collided = False

while Run :
    # [...] 

    Collide()

    SCREEN.fill((83,83,83))        
    if not collided:
        pygame.draw.rect(SCREEN,(0,255,0),Rect)
        pygame.draw.rect(SCREEN,(255,0,0),Rect1)
    pygame.display.flip()

推荐阅读