Skip to content

Algorithms

Jolon Faichney edited this page Mar 24, 2017 · 4 revisions

In the last section we looked at how to approach an entire program by dividing and conquering.

Within our program there may be some tricky pieces of code. These sections of code are not necessarily the entire program and in fact may be a small section of code, but they are difficult and require some serious thought before beginning implementation.

An example, I want to move an object along a trajectory such that it models gravity.

How are we going to solve this problem?

Firstly, what is gravity? Most students should be aware that gravity causes objects to accelerate 9.8 metres per second per second, when falling. It decelerated objects by the same amount when they are moving upwards.

So we need to apply a deceleration/acceleration component to our object as it moves.

Secondly, how fast is the object moving initially? The object will have an initial speed and as it moves upwards it will decelerate until it stops and begins to accelerate to earth.

Let's presume that the initially velocity is v0 and it will be represented in metres per second. The current velocity will be represented by v.

Every second v0 must decrease by gravity, i.e. 9.8 metres per second. Let's assign our 9.8 m/s/s to the variable g.

So it might be tempting to think that we just need to reduce the velocity v by g:

v = v - g;

However, p5.js renders at 30fps. So the amount the object changes per frame will be 1/30th of what it would be per second, the change in velocity per frame will be:

v = v - g / framerate;

Clone this wiki locally