Ball vs ball

We have bothered the walls enough for now, they have been bouncing off the ball well and deserve nice little break, they might like to enjoy little cup of hot coffee or tea (milk, no sugar) while we manage the collision of two balls. The main ball is still moving and so has the movement vector, but other ball doesnt move. Maybe it was nailed on the floor, perhaps it was glued to the ceiling or it may be too small and dumb and just havent learned movement yet.

First lets see how to know if the balls collide and then think what to do with moving ball after the collision.

In the picture ball1 (red) has collided with ball2 (blue). Vector between the center points of both balls is v (green). The collision is happening only, if the length of vector v is less then combined radiuses of both balls. We have to place moving ball just next to other ball and we can do it when we move ball1 back in the direction of v by the amount of:

pen=v.len-(b1.r+b2.r)

Now the balls are placed nice and clean next to each other we need to figure out how to change the movement vector. Imagine non-visible wall placed between two balls and the direction of that wall is exactly same as normal of the vector between centers of balls.

Black vector in the picture is normal of vector v and movement vector of ball1 is calculated as if the ball would bounce from that wall.

I have made an example of 1 ball moving in the stage with several stationary balls:

Try dragging the other balls around.

You can download the source fla of example here.

Keep it in

You may want to keep moving ball inside another (obviously bigger) ball.

In this case big ball is b2 and small moving ball b1. The small ball has moved outside, if

b2.r<(b1.r+v.len)

When that happens we need to move it back in, by the amount of

var pen=b2.r-(b1.r+v.len)

Also, dont forget to reverse the direction of normal of vector v, which is used to bounce off:

var vbounce={dx:-v.dy, dy:v.dx, lx:-v.dx, ly:-v.dy};

You can download the source fla of keeping ball inside ball here. Please notice that this is Flash8 fla.

Next: Moving ball vs ball.

Top