且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python& Pygame:球与圆的内部碰撞

更新时间:2023-08-21 19:14:28

很高兴您喜欢我的教程.我喜欢您的变体,它实际上应该更简单.

I'm glad you liked my tutorial. I like your variation, it should actually be simpler.

首先,我认为您需要将碰撞测试更改为:

First, I think you need change the test for collision to:

if distance >= circle.size - ball.size:

由于球的尺寸越大,其中心与圆心的距离就越小.这应该使球在正确的位置(在圆圈内)弹跳.

Because the larger the ball size, the smaller the distance between its centre and the centre of the circle can be. This should make the balls bounce at the right place (inside the circle).

然后我认为您只需要将x和y的符号交换即可,一切都会正常工作.

Then I think you just need to swap the signs for the x and y and everything should work.

ball.x += math.sin(angle)
ball.y -= math.cos(angle)

要将球移动正确的距离,您可以计算重叠:

To move the ball by the correct distance you can calculate the overlap:

overlap = math.hypot(dx, dy) - (circle.size - ball.size)

if overlap >= 0:
  tangent = math.atan2(dy, dx)
  ball.angle = 2 * tangent - ball.angle
  ball.speed *= elasticity

  angle = 0.5 * math.pi + tangent
  ball.x += math.sin(angle)*overlap
  ball.y -= math.cos(angle)*overlap

祝你好运