[英]Pygame Rect Collision
我正在使用 Python 在 Pygame 中创建 Pong 游戏(显然)并且我是 Pygame 的新手,所以想要一些帮助来处理球接触球拍时的物理学,它会反转速度并朝着相反的方向前进。 到目前为止一切正常,但是当球到达桨时,它会直接穿过它并且不会改变方向。 我已经解决了,所以桨不会离开屏幕,当球碰到墙壁时会改变方向,但当球碰到桨时不会改变方向。 任何帮助或提示将不胜感激。
我的桨类:
class Paddle:
def __init__(self, x, y):
self.x = x
self.y = y
self.height = 40
self.width = 10
def draw(self, canvas):
pygame.draw.rect(canvas, pygame.Color(0,0,255),(self.x,self.y,self.width,self.height))
def contains(self, ptX, ptY):
return self.x < ptX < self.x + self.width & self.y < ptY < self.y + self.height
def overlaps(self, otherRectangle):
return otherRectangle.colliderect(Rect(self.x,self.y,self.height, self.width))
我的球类
class Ball:
def __init__(self, x, y):
#position of ball
self.x = x
self.y = y
#speed of ball
self.dx = 5
self.dy = 5
self.height = 10
self.width = 10
def draw(self, canvas):
pygame.draw.rect(canvas, pygame.Color(0,255,0), (self.x,self.y,self.width,self.height))
def reset(self):
self.x = 320
self.y = 240
self.dx = -self.dx
self.dy = 5
我的目标是让球在接触球拍或反弹(重叠点)时的速度反向(负速度)。
您拥有的代码可能有点过分。 让我们来点更简单的事情。 在你的draw
函数中(在Ball
和Paddle
),继续让你的线条的开始看起来像这样:
self.rect = pygame.draw.rect...
然后你可以使用colliderect函数:
if ball.rect.colliderect(paddle1):
# Reverse, reverse!
对于碰撞使用下面的代码但更改变量
如果paddle1.colliderect(paddle2)或paddle2.colliderect(paddle1):即x轴球方向ballDirectionX*=-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.