How do I create collision detections for my bouncing balls?

后端 未结 7 1239
星月不相逢
星月不相逢 2021-02-04 18:13

I have coded an animation (in python) for three beach balls to bounce around a screen. I now wish to have them all collide and be able to bounce off each other. I would really a

7条回答
  •  梦毁少年i
    2021-02-04 18:46

    Detecting a collision is only the first step. Let's break that down.

    The fastest thing to do is calculate their square bounding boxes and see if those collide. Two of the sides need to cross (top of 1 and bottom or 2, and left of 1 and right of 2, or vice versa) in order for the bounding boxes to overlap. No overlap, no collision.

    Now, when they do overlap, you need to calculate the distance between them. If this distance is more than the sums of the radii of the balls, then no collision.

    Okay! We have two balls colliding. Now what? Well, they have to bounce off each other. Which way they bounce depends on a few factors.

    The first is their elasticity. Two rubber balls bouncing off each other rebound differently than two glass balls.

    The second is their initial velocity. Inertia states that they'll want to keep going in mostly the same direction they started in.

    The third is the mass of the balls. A ball with smaller mass will rebound off a much larger mass with a higher velocity.

    Let's deal with the second and third factors first, since they are intertwined.

    Two balls will rarely hit exactly dead on. Glancing blows are far more likely. In any case, the impact will happen along the normal of the tangent where the balls collide. You need to calculate the vector component of both along this normal given their initial velocities. This will result in a pair of normal velocities that both balls will bring to the collision. Add up the sum and store it somewhere handy.

    Now we have to figure out what each ball will take away from it. The resulting normal velocity of each ball is inversely proportional to the given ball's mass. That is to say, take the reciprocal of each ball's mass, add both masses together, and then parcel out the resultant normal velocity away from the collision based on the ratio of the ball's mass to the sum of the reciprocal of both ball's masses. Then add the tangential velocity to this, and you get the resultant velocity of the ball.

    Elasticity is mostly the same, except it requires some basic calculus due to the fact that the balls are still moving even as they compress. I'll leave it to you to find the relevant math.

提交回复
热议问题