Hack of the day: Implicitly converted booleans
December 15, 2010
In C++ booleans will be implicitly converted to integers when required. You can use this behaviour to create short and readable code.
First of all, a simple example of the players movement found in many games:
// [ ..... ]
Player pl = new Player();
pl->x = 100;
pl->y = 200;
pl->speed = 4;
// [ ..... ]
if (IsKeyDown(CURSOR_DOWN)) { // IsKeyDown returns a boolean
pl.y += pl.speed;
}
if (IsKeyDown(CURSOR_UP)) {
pl.y -= pl.speed;
}
if (IsKeyDown(CURSOR_LEFT)) {
pl.x -= pl.speed;
}
if (IsKeyDown(CURSOR_RIGHT)) {
pl.x += pl.speed;
}
But you don’t need the if statements. Instead you can use the following two lines:
pl.x += (IsKeyDown(CURSOR_RIGHT) - IsKeyDown(CURSOR_LEFT)) * pl.speed; pl.y += (IsKeyDown(CURSOR_DOWN) - IsKeyDown(CURSOR_UP)) * pl.speed;