因此,我尝试使用实例对我的游戏进行碰撞检测。这是代码:
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()
参考方案
首先,在为球创建rect
属性时,该属性应为self.rect = pygame.Rect(x, y, width, height)
(假设您使用import pygame
导入Pygame)。那应该处理您的AttributeError
。 ballRect
,ballRect = pygame.Rect(Ball.coordinateX, Ball.coordinateY, 10, 10)
也是如此。
接下来,您将使用错误的矩形碰撞检测功能。 pygame.sprite
指的是Pygame(它的Sprite
对象)中完全不同的东西,根据您编写的代码,Ball
和Paddle
类都不是Pygame Sprites。因此,在这里调用pygame.sprite.collide_rect()
没有任何意义。
相反,您应该只使用rect.colliderect
,如下所示:
if rect.colliderect(other_rect):
# Colliding!
print("Stop touching me!")
或者您的情况:
if player.rect.colliderect(ballRect):
bounce()
此外,您无需将rect
作为参数传递给Paddle
初始化,因为它从未使用过。对象的rect
完全由您的其他参数生成。
最后,您的Ball
类和实例化代码似乎有些偏离。您应该像对Paddle
一样生成并初始化它。
编辑最后一件事。在pygame中,当您创建具有rect
属性的对象时,您不再需要为该对象分配x
和y
值,因为只要需要它们,例如在blit
中,就可以可以直接传递rect
(在某些情况下为rect.x
和rect.y
)作为position参数,而pygame将很好地处理其余部分。
这是您的代码的外观(已修复其他一些问题):
class Paddle():
def __init__(self, x, y, width, height):
self.width = width
self.height = height
self.rect = pygame.Rect(x, y, width, height)
class Ball():
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
self.velocity = [random.randint(0,1),random.randint(-1,1)]
player = Paddle(1100, 300, 10, 30)
enemy = Paddle(100, 300, 10, 30)
ball = Ball(600, 300, 10, 10)
# Other stuff
# Collision checking
if player.rect.colliderect(ball.rect):
bounce()
“ python setup.py egg_info”失败,错误代码为1。如何解决此问题 - python我该如何解决。我找不到任何带有“ Temp \ pip-install-7utykvpt \ polyglot”的目录C:\Windows\system32>pip install polyglot Collecting polyglot Using cached https://files.pythonhosted.org/packages/e7/9…
AttributeError:模块“ tensorflow”没有属性“ keras” - python最初使用下面的代码加载CIFAR-10数据集。(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() 但是,将Keras安装到环境后,运行上述行会导致错误:>>> AttributeError: module 'tensorflow&…
如何将Moviepy调整为全屏大小? - python我正在使用pygame制作游戏,我想为其添加剪切场景。 pygame电影模块无法正常工作,因此我不得不求助于使用moviepy。从我所看到的内容来看,Moviepy的记录不充分,因此我很难弄清楚。我使用此代码块使它可以工作,但是现在我需要全屏显示(所需的窗口屏幕为640x400)。那我该怎么做呢?先感谢您。from moviepy.editor import…
非面向Ubuntu的pygame平台无法在Ubuntu以外的任何其他设备上正确加载级别 - python我一直在基于this的pygame平台游戏。我是在Ubuntu机器上编写的,它似乎无法在其他操作系统上运行。生成代码是这样的:levelFile = tkFileDialog.askopenfile(mode='r', defaultextension='.lvl', filetypes=[('Level F…
python- sqlite3.OperationalError:“ <”附近:语法错误 - python我正在使用python 3.6。当我尝试实现此功能时,在以下行:cursor = conn.execute(cmd)标题出现错误,有人可以帮我吗?万分感谢。编辑:我已经找到了解决方案,只需将str(id)编辑为str(Id)def getProfile(id): conn=sqlite3.connect("FaceBase.db") cm…