In the post Linear motion we saw how vectors can be used to represent the position and velocity of a moving object. Here we look at how they can be used to simulate the shot fired from a medieval cannon as shown here.
When the cannon is fired the cannon ball will have an initial direction and speed (depending on the barrel elevation and the amount of gunpowder used).
We can see that the cannon ball’s direction (angle) changes throughout it’s flight due to gravity and air resistance so using speed/angle would be computationally demanding. So we are going to use vectors (Processing’s PVector class) to represent the ball’s position and velocity.
So we need some variables to store this data –
int cannon_angle; // degrees PVector cannon_pos; // Cannon ball data PVector ball_pos, ball_vel; float speed = 300; // cannon-shot speed
So the cannon is fired, the first job is to calculate the initial position and velocity of the cannon ball. We can do that with
ball_pos.set(cannon_pos); float angle = radians(cannon_angle); ball_vel.set(speed * cos(-angle), speed * sin(-angle));
The first line initialises the position of the ball to that of the cannon. The angle data is stored in degrees because that is what the human user understands but we must convert it to radians for the trigonometric functions, that is done in the second line. Finally we initialise the velocity vector using the speed and angle. Notice that we negate the angle because the barrel rotation is anti-clockwise.
At each frame we need to update the ball’s velocity to take into account gravity and air resistance, both of which can be represented as vectors. In this sketch we use
gravity = new PVector(0, 100); air = new PVector(-40, 0);
The gravity will only affect the vertical component of the velocity and the air resistance will only affect the horizontal component.
So we update the velocity with
ball_vel.add(PVector.mult(gravity, elapsedTime)); ball_vel.add(PVector.mult(air, elapsedTime)); ball_vel.x = max(ball_vel.x, 0);
where elapsedTime is the number of seconds since the last frame.
The last line prevents the cannon ball reversing its horizontal velocity due to air resistance. In the physical world this is impossible but in our simplistic model, it is a possibility we should guard against.
We can now use this velocity to update the ball’s position with
ball_pos.add(PVector.mult(ball_vel, elapsedTime));
I hope this demonstrates the usefulness of using vectors to represent positions, velocities and forces (gravity and air resistance) to plot non-linear movement.
You can download the sketch used in the production of the movie above here. It is compatible with both Processing 2 & 3.