Game Development Reference
In-Depth Information
name. For example, if you want to check the status of the spacebar, you might be
able to check the index defined by K_SPACE.
Now suppose you are making a simple game where pressing the spacebar causes
your ship to fire a missile. It might be tempting to have code similar to this:
if IsKeyDown(K_SPACE)
fire missile
end
But the problem with this code is that even if the player quickly presses and re-
leases the spacebar, the if statement will be true for multiple consecutive frames.
That's because if the game runs at 60 FPS, the player would have to press and re-
lease the spacebar within the span of 16ms for it to only be detected on one single
frame. Because this is unlikely to occur, each tap of the spacebar would probably
fire three or four missiles on consecutive frames. Furthermore, if the player simply
holds down the spacebar, a missile will fire once per frame until it's released. This
might be the desired behavior, but it also might completely imbalance the game.
A simple but effective improvement is to track the state of the key on both the
current frame and the previous frame. Because there are now two Boolean values,
there are a total of four possible combinations, and each maps to a logically differ-
ent state, as detailed in Table 5.1 .
Table 5.1 Last and Current Key State Combinations
So if on the last frame the spacebar was not pressed, but on the current frame it is
pressed, that would correspond to the “just pressed” result. This means if the mis-
sile fire action were instead mapped to a “just pressed” spacebar action, the ship
would only fire one missile per discrete button press.
This system also provides more flexibility than the previous approach. Suppose
our game allows the player to charge up his missile the longer he holds down the
Search WWH ::




Custom Search