我正在用 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
我的目标是当球接触球拍或反弹(重叠点)时使球的速度反转(负速度)。