回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我在做一个游戏,球在一个大得多的圆的内部反弹。大圆圈不动。</p>
<p>下面是我当前用于这些冲突的代码:</p>
<pre><code>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)
</code></pre>
<p>它是基于彼得·柯林格里奇的精彩教程<a href="http://www.petercollingridge.co.uk/pygame-physics-simulation/collisions" rel="noreferrer">over here</a>。</p>
<p>圆和球对象都是类,具有(x,y)、半径、角度和速度。</p>
<p>但是,我对这种方法有两个问题:</p>
<ol>
<li>球从(我怀疑)它的“锚点”反弹,它似乎在圆圈的右上角。</li>
<li>当与底部5%的圆圈相撞时,它无法反弹到足够高的高度,因此“下沉”出屏幕。我猜这是因为弹跳不够高,无法将球移动到其(错误放置的)“锚点”上方?</li>
</ol>
<p>在研究了可能的解决方案之后,特别是“快速圆碰撞检测”[由于垃圾邮件链接限制而删除的链接],虽然在Java中使用的是相同的方法,但这些都是处理外部碰撞的,而我正在研究的是将球反弹到圆的内部。</p>
<p>下面是Ball()和Circle()的类定义:</p>
<pre><code>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
</code></pre>
<p>提前谢谢你,内森</p>