All the comments and answers are great to help you understand how it is possible. But, here's something that will help you understand how it's actualized!
It is a tiny IC (3x3x1 mm!) by InvenSense. It has a three-axis accelerometer (for lateral movement), a three-axis gyroscope (for rotation), and a three-axis magnetometer (like a compass needle). It has internal code which will do all the complicated math. It takes almost no power. All this for $10 in single quantities.
This is only an example. There are several companies making similar products. Some are more accurate than others, some are cheaper, most don't have the magnetometer, etc...
Have fun!