Game Development Reference
In-Depth Information
small distance and it is close to the origin (i.e., its coordinates are close to zero), the
object will be moved correctly. If you move the same object the same distance, but it
is far away from the origin, then you may end up with no movement or too large a
movement, depending on the order of your mathematical operations.
When you are using the physics engine with a broad range of masses, velocities,
or positions, this can be a problem. Visually it can range from objects sinking into the
ground or collisions having no effect, to suddenly disappearing bodies and collisions
occurring in completely the wrong direction. It is a common problem in collision
detection algorithms too, where objects can be reported as touching when they are
separate, or vice versa.
There is no definitive solution to this problem, but you can increase the accuracy
of the mathematics being performed. In C++ you can switch from float sto double s,
which take up twice the amount of memory, take a little less than twice the amount
of time to process, but have millions of times the accuracy.
I have placed all the code on the CD that deals with the accuracy of the engine into
the include/cyclone/precision.h file. This defines the real data type, which is used
for all floating-point numbers. The real data type can be defined as a float or as a
double . As well as the data type, I have given aliases for some mathematical functions
in the standard C library. These need to be reset to call the correct precision version.
The single-precision code has been quoted so far. When compiling in double-
precision mode these definitions become
Excerpt from include/cyclone/body.h
#define DOUBLE_PRECISION
typedef double real;
#define REAL_MAX DBL_MAX
#define real_sqrt sqrt
#define real_abs fabs
#define real_sin sin
#define real_cos cos
#define real_exp exp
#define real_pow pow
#define R_PI 3.14159265358979
You can see this code in the precision header, along with an ifdef to select the defin-
itions you need.
I tend to compile with double precision by default. On a PC the performance hit
is relatively minor. On some consoles that are very strongly 32-bit, the 64-bit mathe-
matics is very slow (they perform the mathematics in software rather than hardware,
and so are much more than twice as slow in most cases), so single precision is crucial.
For objects with similar masses, low velocities, and positions near the origin, single
precision is perfectly fine to use. The demonstration programs on the CD work well
in either precision.