Game Development Reference
In-Depth Information
The script begins by storing the original local position and rotation of the gun. This step
is necessary to insure that we return the gun to its original position after animating it. The
script also needs a reference to
RaycastShooter
, in order to read inaccuracy values and
use them in the animation. One additional interesting variable here is
zDistance
, which
is the amount of movement on the local z axis of the gun. When the player shoots, the
gun moves very fast (instantly, in fact) to this z position, in order to simulate shooting
reaction. After that, the gun return slowly and smoothly to its original position. In ad-
dition to the movement along z axis, the gun rotates around its local x and y axes by
the values of last inaccuracy vector accessed through
shooter.GetLastInaccuracyVector()
.
In
LateUpdate()
, we make sure that the gun returns to its original position by calling the
functions
Vector3.Lerp()
for the position and
Quaternion. Lerp()
for the rotation. However,
we multiply
Time.deltaTime
by 10 in order to get a faster return, which is needed in case of
high shoot rate.
Up to now, we have a physical first person character that can move, jump, push objects, and
aim at them using a gun with a crosshair. The remaining step in regard to character is giving
the player the ability to shoot using mouse button. This task is as simple as reading mouse
input and calling
Shoot()
function from
RaycastShooter
script. Listing 51 shows
GunInput
script, which reads mouse input and triggers the shooter.