【问题标题】:Deleting Sprites in Pygame在 Pygame 中删除精灵
【发布时间】:2013-07-16 15:09:52
【问题描述】:

我有一个通过类似这样的 for 循环运行的平铺地图:

def Draw_Level( x, y, column, obsticles, entities, image_cache ):

    #Grass#
    if column == "G":
        g = Grass(x, y, image_cache)
        entities.add(g)
    #Plain Grass#
    elif column == "P":
        p = Plain_Grass(x,y, image_cache)
        entities.add(p)
    #Grass with yellow flower#
    elif column == "F":
        f = Grass_Flower(x,y, image_cache)
        entities.add(f)
    #Grass To Sand (50/50 split block) Direct#
    elif column == "Y":
        q = Grass_To_SandD(x,y, image_cache)
        entities.add(q)

#Example If a class
class Grass(Entity):

    def __init__(self, x, y, image_cache):
        Entity.__init__(self)
        self.image = functions.get_image("data/images/Grass.png", image_cache)
        self.image.convert()
        self.rect = Rect(x, y, 32, 32)

比如说,我的鼠标点击了其中一个,x 和 y 被确定为最接近的 32(即块的宽度和高度)。我如何确定点击了哪个精灵?例如,如果我点击了一个“草”块,该块的坐标在屏幕上绘制,我该如何删除它?

Entites = 包含所有实体的列表

有没有办法从实体列表中调用它?它让我通过列表调用 Rect 感到困惑,所以这就是我被卡住的原因:S.

【问题讨论】:

    标签: python python-2.7 pygame


    【解决方案1】:

    您想要做的称为“命中检测”或“hit-testing”。对于您的代码,它需要遍历实体列表并检查鼠标单击的 x、y 位置与每个实体所占据的矩形范围。

    如果您将每个类都设为一个类,则可以向它们添加一个方法 hit_test(self, x, y) 并在每个类上调用它。大致如下:

    class Grass(Entity):
        def __init__(self, x, y, image_cache):
            Entity.__init__(self)
            self.image = functions.get_image("data/images/Grass.png", image_cache)
            self.image.convert()
            self.rect = Rect(x, y, 32, 32)
        def hit_test(self, x, y):
            return (self.rect.x <= x < self.rect.x+self.rect.width and 
                    self.rect.y <= y < self.rect.y+self.rect.height) 
    

    【讨论】:

    • 谢谢,我设法得到它。另外,感谢您提供有关命中测试的信息。
    • 不客气。请注意,这可以通过预先计算 x 和 y 边界并将它们存储在实体中来加速。同样,如果鼠标 x,y 在包含所有这些的(想象的)边界框之外,您可以通过不检查它们中的任何一个来将相同的逻辑应用于堆叠在一起的整个组。这称为“trivial rejection”,用于剪线。
    【解决方案2】:

    您可以使用rect.collidepoint 来确定鼠标光标是否在矩形内。

    entities_the_mouse_is_over = [entity for entity in entities if entity.rect.collidepoint(mouse_x, mouse_y)]
    

    如果您希望使用这种方法,请重新考虑您的舍入算法。当mouse_xmouse_y 被四舍五入到最接近的32 时,这将不起作用。例如,假设一个磁贴的矩形为(0,0,32,32),并且用户在(20,20) 处单击。 mouse_xmouse_y 将四舍五入到 (32,32),就 collidepoint 而言,它不在 rect(0,0,32,32) 内。

    如果您只对向下进行四舍五入,那么collidepoint 将起作用。在前面的示例中,(20,20) 将向下舍入为 (0,0),即在 rect(0,0,32,32) 内。

    您也可以根本不进行任何舍入。

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多