How do I delete rect object from screen once player collides with it?

≡放荡痞女 提交于 2021-02-02 09:35:28

问题


in draw() function I am trying to delete rect object when player pos = enemy pos but "del" will not work. Any way to delete the enemy object completely? Is there a built in pygame function to delete objects that I don't know about?

# draw player
def draw():
    enemy = pygame.draw.rect(screen, enemy_color, (enemy_x, enemy_y, 25, 25))
    player = pygame.draw.rect(screen, player_color, (player_x, player_y, 25, 25))
    
    # if the player is over the enemy then delete the enemy
    if player_x == enemy_x and player_y == enemy_y:
        # this does not work
        del enemy

回答1:


You cannot "delete" something" what is draw on a Surface. A Surface contains just a bunch pixel organized in rows and columns. If you want to "delete" the rectangle, then you must not draw it.
Create to pygame.Rect and do the collision test before. For instance:

def draw():

    enemy_rect = pygame.Rect(enemy_x, enemy_y, 25, 25)
    player_rect = pygame.Rect(player_x, player_y, 25, 25)

    if player_rect.colliderect(enemy_rect):
        # create new enemy
        # [...]
    else:
        enemy = pygame.draw.rect(screen, enemy_color, enemy_rect)
    
    player = pygame.draw.rect(screen, player_color, player_rect)

Anyway I recommend to use pygame.sprite.Sprite objects organized in pygame.sprite.Group. pygame.sprite.Sprite.kill remove the Sprite from all Groups.



来源:https://stackoverflow.com/questions/62957899/how-do-i-delete-rect-object-from-screen-once-player-collides-with-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!