Game Development Reference
In-Depth Information
The main function of this script is
Shoot()
, in which the ray casting is performed. Before
shooting, the function checks whether minimum time gap between two consecutive shoots
has already passed. If this is true, it generates two random numbers for x and y inaccuracy
angles. The horizontal inaccuracy is a random value between
-horizontalInaccuracy
and
+horizontalInaccuracy
, and, similarly, the vertical inaccuracy is generated in the
range[-
verticalInaccuracy
,
+verticalInaccuracy
]. The generated random values are stored in
x
and
y
members of
inaccuracyVector
. Initially, the muzzle must be positioned so that its
positive z axis points forward towards shooting direction. Before shooting, we rotate the
muzzle around its local x and y axis by the values of the two generated inaccuracy angles.
After performing inaccuracy effect, we are now ready to perform the actual shooting. The
variable
hit
declared in line 56 is the place were hit data are going to be stored (if there is a
hit surely). In line 59 through 61 we call
Physics.RayCast()
, in order to perform shooting.
The ray starts from the position of the muzzle and heads towards the direction of its pos-
itive z axis. The variable
hit
is provided as store place for hit data using the keyword
out
.
This keyword marks an output parameter, unlike input parameters we are used to use when
calling functions. In other words, the function
Physics.RayCast()
is going to set the value
of
hit
, instead of reading its value. Finally, we tell the function that the length of the ray
must not exceed the value of
maxRange
. Lines 66 through 70 are executed if the ray has
hit something. The variable
hit.distance
stores the distance between ray generation position
and the object that has been hit by the ray. We need this distance in order to compute the
scaled damage we are going to apply to the hit object.
Remember that we store the damage of the bullet in the variable
power
, which is the
damage applied to the object when shot from zero-distance. As the distance between the
shooter and the target increases, the damage caused by the bullet decreases linearly, until
it reaches zero at
maxRange
. When the bullet hits the target, the damage it causes interests
us more than the distance from which it has been shot. Therefore, we compute the damage
based on the distance, and them overwrite
distance
member of
hit
variable with the scaled
damage (lines 66 and 67). Finally, we inform the target that it has been hit by sending
OnRaycaseHit
message to it and providing
hit
, which contains necessary data such as
damage and direction.
When shooting is completed, we have to return the muzzle back to its original rotation by
rotating it again with the negatives of random inaccuracy variables. After that, the current