SFML C++ 2D Physics Simulator
For this project, I decided to try working at a lower level by coding a simple 2D physics engine from scratch. I found SFML (Simple Fast Multimedia Library), which is a library that provides functionality for opening windows, rendering images, handling events such as mouse clicks or keyboard inputs, and so on, which is what I needed. It is also based on C++, which I wanted to practise using.
I started by rendering a circle and making it move in response to the arrow keys being pressed. It turns out that an object's speed can be simulated by multiplying the time elapsed since the start of a frame by a set value and updating the position each frame. Then, acceleration occurs when this value changes between frames. Given control over acceleration, you could simulate forces such as gravity and drag.
I then made it so that while you are pressing an arrow key, the circle accelerates in that direction. Then, once you let go, drag 'activates' and it decelerates in the opposite direction until its velocity in that axis reaches zero. This worked, but since the x-y components of the object's velocity were independent, they would independently decelerate. This meant that if you accelerated it different amounts on the two axes, the object would suddenly change direction when decelerating, which is not very Newtonian.
I fixed this by introducing polar coordinates. The arrow key 'forces' would modify the velocity's cartesian coordinates, while drag would act on the magnitude of the velocity vector, regardless of which way it was directed. So one object would have two sets of coordinates that would update each other in response to these modifiers. I also added gravity, which just always accelerates the object down. The result may be seen in the video below.
What I learnt:
- SFML: linking libraries to projects with CMake, structure of SFML application (main loop, input handling, time handling, renderning), velocity/acceleration simulation.
- C++: cmath, using references.
In the future, I would like to expand this engine to account for more factors such as collisions, friction, rotational stuff, maybe vibrations, etc. I would also like to make more use of C++'s classes to make my code more general and reusable.