#define TABLE_SIZE 360
float sinTable[TABLE_SIZE];
float cosTable[TABLE_SIZE];
void buildTrigTables() {
for (int i = 0; i < TABLE_SIZE; i++) {
float angle = i * (3.14159265f / 180.0f);
sinTable[i] = sinf(angle);
cosTable[i] = cosf(angle);
}
}
Instead of:
float s = sinf(angle);
float c = cosf(angle);
Use:
float s = sinTable[angle];
float c = cosTable[angle];
This is dramatically faster on old CPUs.
Rotating a 2D point requires sine and cosine:
float s = sinTable[angle];
float c = cosTable[angle];
float rx = x * c - y * s;
float ry = x * s + y * c;
| System | Usage |
|---|---|
| Player rotation | Turning characters or vehicles |
| Camera movement | Orbit and aiming systems |
| Bullets | Projectile direction |
| Particles | Explosion movement |
| Physics | Velocity direction |
| Sprites | 2D sprite rotation |
| Benefit | Why It Matters |
|---|---|
| Very fast | Memory access is faster than trig calculations |
| Low CPU usage | Excellent for old hardware |
| Deterministic | Always returns the same values |
| Simple implementation | Easy to integrate into engines |
| Problem | Description |
|---|---|
| Memory usage | Tables consume RAM |
| Precision limits | Depends on table size |
| Angle wrapping | Need modulo handling |
Angles should wrap around the table size.
angle %= TABLE_SIZE;
Larger tables provide smoother rotations.
| Table Size | Precision |
|---|---|
| 360 | 1 degree |
| 1024 | Common retro choice |
| 2048 | Very smooth |
| 4096 | High precision |
Some retro engines used fixed-point trig tables:
int16_t sinTable[1024];
This reduced memory usage and improved performance.
Lookup tables were heavily used in:
Retro optimization is about replacing expensive operations with predictable and cache-friendly operations.
A lookup table transforms:
CPU-heavy math
into:
Fast memory access