以下是我目前用于处理碰撞的代码:
def collideCircle(circle, ball):
"""Check for collision between a ball and a circle"""
dx = circle.x - ball.x
dy = circle.y - ball.y
distance = math.hypot(dx, dy)
if distance >= circle.size + ball.size:
# We don't need to change anything about the circle, just the ball
tangent = math.atan2(dy, dx)
ball.angle = 2 * tangent - ball.angle
ball.speed *= elasticity + 0.251
angle = 0.5 * math.pi + tangent
ball.x -= math.sin(angle)
ball.y += math.cos(angle)
这是基于Peter Collingridge的优秀教程(链接在此)。
圆形和球体均为类,包含(x, y), 半径, 角度和速度。
然而,我遇到了两个问题:
- 球从其“锚点”(我认为)反弹,该点似乎位于圆的右上角。
- 当与圆的底部5%相撞时,它未能反弹高到足以将球移出屏幕,我猜测这是因为反弹不够高,无法将球移动到其(放置不正确的)“锚点”上方?
已经在这里查看了可能的解决方案,特别是“快速圆形碰撞检测”[由于垃圾邮件链接限制已删除链接],虽然使用相同的方法,但这些都处理外部碰撞,而我正在考虑将球弹在圆的内部。
以下是Ball()和Circle()的类定义:
class Ball():
def __init__(self, (x,y), size):
"""Setting up the new instance"""
self.x = x
self.y = y
self.size = size
self.colour = (0,128,255)
self.thickness = 0
self.speed = 0.01
self.angle = math.pi/2
def display(self):
"""Draw the ball"""
pygame.draw.circle(screen, self.colour, (int(self.x), int(self.y)), self.size, self.thickness)
def move(self):
"""Move the ball according to angle and speed"""
self.x += math.sin(self.angle) * self.speed
self.y -= math.cos(self.angle) * self.speed
(self.angle, self.speed) = addVectors((self.angle, self.speed), gravity)
self.speed *= drag
class Circle():
def __init__(self, (x,y), size):
"""Set up the new instance of the Circle class"""
self.x = x
self.y = y
self.size = size
self.colour = (236, 236, 236)
self.thickness = 0
self.angle = 0 # Needed for collision...
self.speed = 0 # detection against balls
def display(self):
"""Draw the circle"""
pygame.draw.circle(screen, self.colour, (int(self.x), int(self.y)), self.size, self.thickness
事先感谢您,Nathan