Game Development Reference
In-Depth Information
Sometimes we need to read the key only once instead of the repetitive reading in every
frame. For instance, the jump action in platformer games usually requires the player to
release the jump button/ key and press it again to make a new jump, instead of jumping
continuously by simply keeping the jump key pressed. For similar scenarios, we use In-
put.GetKeyDown() , which gives us true only at the first time the player presses the key. After
that, it keeps returning false until the key is released and pressed again. You can examine
the difference between Input.GetKey() and Input.GetKeyDown() by replacing one by another
in Listing 4.
If you are not familiar with programming, and hence do not really recognize the difference
between using if alone and else if ; I will explain this with the help of Listing 5. By using
only if , we allow each key to be scanned independently, which in turn allows all keystrokes
to affect the object simultaneously. So if the player holds both up arrow and right arrow,
the object will move on both x and y axes resulting in diagonal displacement. However, if
the player presses up and down arrows together, they will cancel each other effects and the
object isn't going to move at all. Here where else if comes into play. If we want to prevent
reading two opposite directions at the same time, we use else if and hence give the priority
to the key that has the first condition check.
Search WWH ::




Custom Search