Rigidbody #1: Linear Forces

In this first installment of my 2D rigidbody tutorial, we are going to explore linear forces and how we can begin to simulate them in real time on a computer. As you'll come to see, 2D forces are quite easy to understand and implement if you have some basic knowledge of 2D maths. On top of that, they really add a lot of life into what would otherwise be a static 2D scene.

What do we mean by 'Rigid Body Physics'?

In implementing a rigidy body physics system, we're primarily interested in two sub-fields of physics, namely dynamics and kinematics. Although I'm far as can be from being an expert in either of these fields, I will explain - from a programmer's perspective - what they mean to me: Although the distinction between these two subfields may seem inconsequential, it impacts the conceptual way in which we might begin to setup our 2D rigidbody simulation: the kinematic variables are the data that we act upon, while the dynamics variables are the data that we apply.

The Kinematics Data Structure

Now that we have that understanding, we can begin setting up our rigidbody data structure. #SNIPPET rigidbody_1/snippet1.cpp As you can see, the base data structure exactly mirrors what we already know from 2D newtonian physics.

The Dynamics Functions

Now, let's put that Rigidbody data structure to work! As I mentioned earlier, you can think of dynamics as the input to the system. What we're going to do now is add a way to #SNIPPET rigidbody_1/snippet2.cpp

Live Example

That's all there is to a rigidbody system with 2D linear forces. Now let's see it in action. Click 'Play' on the WebAssembly demo below to see a square bouncing around the screen. When you drag the pointer through the square, we will apply a force equivalent to how fast you were moving your mouse in the direction that you were moving it. (The speed is capped in the demo, or else things get a little out of hand.)