因此,我尝试使用实例对我的游戏进行碰撞检测。代码如下:
class Paddle:
def __init__(self, x, y, width, height, rect):
self.x = x
self.y = y
self.width = width
self.height = height
self.rect = pygame.rect.Rect(x, y, width, height)
class Ball:
coordinateX = 600
coordinateY = 300
velocity = [random.randint(0,1),random.randint(-1,1)]
player = (Paddle(1100, 300, 10, 30, (1100, 300, 10, 30)))
enemy = Paddle(100, 300, 10, 30, (100, 30, 10, 30))
ball = (Ball.coordinateX, Ball.coordinateY, 15)
后来:
ballRect = pygame.rect.Rect(Ball.coordinateX, Ball.coordinateY, 10, 10)
if pygame.sprite.collide_rect(player, ballRect):
bounce()
正如模块名“sprite”所提示的那样,函数
pygame.sprite.collide_rect
和所有其他冲突检测函数期望Sprite
实例作为参数请看documentation:
(另外,通常不直接使用此函数,而是与^{} 一起使用)
因此,要么开始使用} :
Sprite
类(这是您应该做的),要么使用Rect
类提供的函数,如^{首先,当为球创建
rect
属性时,它应该是self.rect = pygame.Rect(x, y, width, height)
(假设您使用import pygame
导入Pygame)。这应该可以处理你的AttributeError
。你的ballRect
,ballRect = pygame.Rect(Ball.coordinateX, Ball.coordinateY, 10, 10)
也是如此接下来,您使用了错误的rect碰撞检测功能
pygame.sprite
指的是Pygame中完全不同的东西(它的Sprite
对象),并且您的Ball
和Paddle
类都不是您编写的代码中的Pygame精灵。因此,在这里调用pygame.sprite.collide_rect()
没有任何意义相反,您应该简单地使用
rect.colliderect
,如下所示:或者在您的情况下:
此外,您不需要将
rect
作为参数传递给Paddle
初始化,因为它从未被使用过。对象的rect
完全由其他参数生成最后,您的
Ball
类和实例化代码似乎有点不对劲。您应该像对Paddle
一样生成并初始化它编辑最后一件事。在pygame中,当您创建一个具有
rect
属性的对象时,您不再需要为该对象分配x
和y
值,因为无论何时需要它们,例如在blit
中,您都可以直接传递rect
(或者在某些边缘情况下,rect.x
和rect.y
作为位置参数,pygame将很好地处理其余的问题下面是您的代码应该是什么样子(还有一些其他问题需要解决):
根据documentation,
pygame.sprite.collide_rect()
用于检测两个精灵之间的碰撞,但是您正在通过一个pygame.rect.Rect()
对象和一个拨片对象因此,如果您想使用
pygame.sprite.collide_rect()
,您需要做的是使用pygame.sprite.Sprite
创建两个对象,然后检测它们之间的冲突相关问题 更多 >
编程相关推荐