Python & Pygame: Ball collision with interior of circle

前端 未结 3 539
时光取名叫无心
时光取名叫无心 2021-01-18 04:16

I\'m making a game in which balls bounce around the inside of a much larger circle. The larger circle doesn\'t move.

Here\'s the code that I\'m currently us

3条回答
  •  礼貌的吻别
    2021-01-18 04:34

    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).

    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
    

    Good luck

提交回复
热议问题