How do I create collision detections for my bouncing balls?

后端 未结 7 1234
星月不相逢
星月不相逢 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条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 18:31

    Collision detection for arbitrary shapes is usually quite tricky since you have to figure out if any pixel collides.

    This is actually easier with circles. If you have two circles of radius r1 and r2, a collision has occurred if the distance between the centers is less than r1+r2.

    The distance between the two centers (x1,y1) and (x2,y2) can be calculated and compared as:

    d = sqrt((y2-y1) * (y2-y1) + (x2-x1) * (x2-x1));
    if (d < r1 + r2) { ... bang ... }
    

    Or, as jfclavette points out, square roots are expensive so it may be better to calculate using just simple operations:

    dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1);
    if (dsqrd < (r1+r2)*(r1+r2)) { ... bang ... }
    

    The tricky bit comes in calculating the new movement vectors (the rate at which (x,y) changes over time for a given object) since you need to take into account the current movement vectors and the point of contact.

    I think as a first cut, you should just reverse the movement vectors to test if the collision detection works first.

    Then ask another question - it's better to keep individual questions specific so answers can be targeted.

提交回复
热议问题