A Force to be Reckoned With

Newton’s second law states that Force = Mass * Acceleration and with this simple statement we can add forces to our objects. To simplify things, we’ll say for now that all of our objects have a mass of one, which simplifies the expression to Force = Acceleration, therefore we can simply apply the net of any forces that we want to interact with the object and we should get a reasonable result. We will also need to zero out the acceleration on the object after each update to prevent the previous frames acceleration from accumulating with the next frame and so on.

We will be modifying our mover class to add an applyForce() function and also to nullify the acceleration at the end of the update() function.

[pastacode lang=”cpp” manual=”void%20mover%3A%3Aupdate()%0A%7B%0A%20%20%20%20velocity.add(acceleration)%3B%0A%20%20%20%20velocity.limit(maxSpeed)%3B%0A%20%20%20%20position.add(velocity)%3B%0A%20%20%20%20acceleration.mult(0)%3B%0A%7D%0A%0Avoid%20mover%3A%3AapplyForce(vec2%20force)%0A%7B%0A%20%20%20%20acceleration.add(force)%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

 

Now if we add a force vector, say wind which could be a vector of 1,0 and we apply that force to the ball object, we should see the ball begin to accelerate, this affect is more obvious if we make it so that the mouse button triggers the force:

[pastacode lang=”cpp” manual=”case%20SDL_MOUSEBUTTONDOWN%3A%0A%20%20%20%20%20%20%20%20ball.applyForce(wind)%3B%0A%20%20%20%20%20%20%20%20break%3B” message=”” highlight=”” provider=”manual”/]

Adding this to our existing event handler allows us to add the force when the button is pressed, this won’t work for holding, we’ll need a different solution for click and hold, but this works for the purposes of exploration.

Next we can add gravity to be added at each frame by simply adding a gravity force, which is essentially a downwards facing wind force: vec2 gravity(0,1).

Interestingly this does not have the anticipated result of the ball continuing to move at a diagonal,  we’ll have to dig a little deeper and see what is going on!

 

Leave a Reply

Your email address will not be published. Required fields are marked *