Pujan_OP
Pujan_OP

Reputation: 9

Delete OBJECT in Pygame?

Hello guys i am just trying make something cool and i canot get how to Delete an drawn OBJ in pygame I get error while using remove() , Delete()

HERE is the code :

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()

Waiting for some answers .

Upvotes: 0

Views: 610

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

You cannot "delete" something what is draw on the screen respectively on a Surface. A Surface contains just a bunch pixel organized in rows and columns. If you want to "delete" an object, then you must not draw it.

e.g.:

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()

Upvotes: 1

Related Questions