Game Development Reference
In-Depth Information
Listing 84:
A script to handle weapon switching, firing, and reloading
All weapons we use must be added to
weapons
array, so that they can be accessed by the
script and hence the player has the ability to switch between them. By default,
initialWeapon
is set to -1. After adding the script to player's game object and adding our three weapons to
weapons
array, we can set
initialWeapon
to 0, 1, or 2. The currently hold weapon is managed
by the script internally through
currentWeapon
, so the only way to change the current
weapon is by calling
SetCurrentWeapon()
function. This is necessary to make sure that
RefreshInHandValues()
is called each time we switch the weapon. The importance of this
function is that it guarantees having only one weapon that has
true
value for
inHand
. This
weapon is in fact the one in the index
currentWeapon
in
weapons
array. During each frame up-
date,
UpdateSwitching()
and
UpdateShooting()
are invoked.
UpdateSwitching()
scans keyboard keys starting from
KeyCode.Alpha1
.
KeyCode.Alpha1
is
the key with digit 1 found on the the upper left corner of the keyboard. If we convert
KeyCode.Alpha1
to integer and add 1 to it, we get an integer value equal to
KeyCode.Alpha2
. This fact is useful for us in scanning all numeric keys using
for
loop
instead of writing a specific
if
statement for each key. As a result, the key with digit 1
matches the weapon in index 0 in
weapons
and so on. On the other hand,
UpdateShooting()
reads input from mouse buttons. It calls
Fire()
function from the current weapon when