本文介绍了一旦玩家与它发生碰撞,如何从屏幕上删除 rect 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

in draw() 函数我试图在玩家 pos = 敌人 pos 但del"时删除矩形对象不管用.有什么办法可以彻底删除敌人对象?是否有内置的 pygame 函数来删除我不知道的对象?

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

推荐答案

您不能删除"东西"在 Surface 上绘制什么.Surface 仅包含按行和列组织的一堆像素.如果您想删除"矩形,那么你一定不要画它.
创建 pygame.Rect 并进行碰撞之前测试.例如:

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)


无论如何我建议使用 pygame.sprite.Sprite 对象组织在 从所有组中删除 Sprite.


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

这篇关于一旦玩家与它发生碰撞,如何从屏幕上删除 rect 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 16:32