Durham Hackathon

A short intro to numerical simulation

View on GitHub

Previous step

How to bounce a ball

Next let’s simulate what happens when we hit the floor. What we expect is that the ball (if it is perfectly elastic) will bounce back up. In a perfectly elastic collision no energy is lost, that’s not entirely realistic but it is where we will start.

So the ball needs to change direction, or in other words, the velocity of the ball will change signs:

\[v \rightarrow -v\]

In order to keep the momentum we also need to modify the position in y slightly (we want to bounce of the actual wall not somewhere slightly below it):

\[y \rightarrow y - g t^2\]

You will need to know the location of the floor as well. At the top you will see the size of the screen being set to width and height. Use these for your checks. The canvas is centered at 0. That means the floor will be at -height/2 and the ceiling at height/2. The walls are analogously at -width/2 and width/2.

Add bounce:


 

After you’ve got it bouncing off the floor introduce a ceiling and walls. The ball should bounce of the ceiling and the walls in the same way as it does off the floor. What do you need to change? What remains the same?

You will need to introduce a second velocity component. So now you have \(v_x\) and \(v_y\) giving the \(x\) and \(y\) components of the velocity. To bounce off a ceiling or floor we modify the \(y\) component of the velocity, to bounce off of a wall we modify the \(x\) component.

Modify your while loop to include updates to the \(x\)-coordinate of the ball and the \(x\) velocity of the ball. Bear in mind that gravity does not act in the horizontal plane.

To test these you need to modify the starting velocity which is currently set to 0 in \(x\) and \(y\) directions.

Fancy a hint? You can find the solution here.

Next step