Monday, 20 February 2012

ball-wall collisions

Collisions between a ball (in two or three dimensions) are perhaps the simplest to code. This is one consequence of the mathematical simplicity of ball physics, as discussed in my last post. As long as certain assumptions are made the code for such collisions is only a couple of very simple lines.

It is worth making note of the assumptions. First as in previous ballistics examples (which this is forked from) the code assumes there is no air resistance or drag. This is a common assumption to make as although unrealistic the result is perhaps more intuitive, giving a symmetric parabolic path. For a heavy projectile fired at not too high a speed it is a very good approximation.

The other main assumption is that the missile is smooth. This is so when it is in collision it only picks up speed in the direction away from the collision surface. It does not pick up any rotational speed and start rolling.

The code looks like this: this is not just the collision code but all of the dynamics update code. First it updates the speed and position of the missile. It then checks if it is below the ground (distance being measured down the page) and if so it moves it above, multiplying its vertical speed by -0.8

fBallV += fGravity; 
fBallX += fBallU;
fBallY += fBallV;
if (fBallY > fMax) {
    fBallY = 2 * fMax - fBallY;
    fBallV *= -0.8;

This last line is the key. The number 0.8 is the coefficient of restitution, a measure of the amount of bounce of the collision. It goes from 0 to 1, with 0 being no bounce (it just sticks to the surface), 1 being a perfect collision. A value of 0.8 is at the high end of what's realistic for an elastic ball.

The simulation aims like the previous version but doesn't stop when it reaches the target but keeps running until the ball goes off the side of the game area, bouncing to keep from falling off the bottom edge.

No comments:

Post a Comment