pygame 中的碰撞检测。错误:没有属性“矩形”

问题描述 投票:0回答:1

pygame 新手,编写一些代码来尝试检测碰撞。这是我编写的一个小测试文件来演示该错误。它实例化两个精灵,并尝试检测它们之间的碰撞

import pygame

class Box(pygame.sprite.Sprite):
    def __init__(self):
        self.name = "foo"
class Circle(pygame.sprite.Sprite):
    def __init__(self):
        self.name = "bar"

box = Box
circle = Circle

pygame.sprite.spritecollideany(box, circle)

但是这会返回错误:

    default_sprite_collide_func = sprite.rect.colliderect
                                  ^^^^^^^^^^^
AttributeError: type object 'Box' has no attribute 'rect'

我不太确定应该做什么来纠正这种情况。如何检测 pygame 中两个精灵之间的碰撞?

python pygame sprite collision-detection
1个回答
0
投票

spritecolllideany函数以

(sprite, group)
为参数,即第一个参数是一个精灵实例,第二个参数是一个精灵组(其中包含一个或多个精灵实例)。

在您的示例代码中,您正在传递 classes;它相当于:

pygame.sprite.spritecollideany(Box, Circle) # passing the class objects, oops!

错误消息可能有点令人困惑,但它提供了有关正在发生的事情的一些很好的线索:它本质上是说

Box
class 没有名为
rect
的属性(如果已传入 instance) ,而不是显示
type object 'Box'...
的错误,而是显示
'Box' object...
)。

您可能需要更多类似的东西:

box = Box() # create an instance
circle = Circle()
group = pygame.sprite.Group() # create a group with a sprite in it
group.add(circle)
hit = pygame.sprite.spritecollideany(box, group)
if hit:
  ... # there was a collision...

请注意,您的子类不会调用基类

Sprite
__init__
方法,而您可能想要这样做。另外,您的精灵子类当前不执行任何操作 - 例如,您想让它们绘制图像。

我知道您提到您的示例代码只是一个精简的示例,所以也许您已经在实际代码中执行了这两件事。如果没有,黑猩猩示例将引导您完成其中的一些内容。

© www.soinside.com 2019 - 2024. All rights reserved.