Game Development Reference
In-Depth Information
To hold an object, we perform a number of steps. We begin by getting all holdable objects
in the scene and iterate over them (lines 21 through 23). For each object, we compare the
distance between it and the holdable, and if the distance is less than the sum of radii, the
value of close variable becomes true (lines 26 through 33). The true value of close means
that the object is close enough to be hold. However, there is another condition to check. It is
necessary for the holder to face the holdable object before being able to hold it. This con-
dition can be checked by measuring the angle between holder's looking direction ( trans-
form.forward ) and the straight line between the position of the holder and the position of
the holdable (lines 36 through 42). Vector math tells us that we have to subtract the position
of the holder from the position of the holdable, in order to get a vector that represents the
line between these two objects. If the angle between these two vectors is less than 90, we
consider this as facing (line 44).
After checking all relevant condition, it is time to do the actual holding of the holdable
object. This step is fairly simple. Firstly, we have to store the holdable we found in
objectInHands variable. Since the value of this variable is not null anymore, no other object
can be hold, and pressing E again is going to release it. Secondly, we set the parent of the
holdable transform to be the holder itself. By doing this, we ensure that the holdable moves
with the holder wherever it goes, and rotates with it as well (lines 44 through 51). In line
53, we use return to stop the execution of Update() . This step enhances the performance by
avoiding unnecessary check of the rest of holdable objects, since we have already found
what we need. Lines 57 through 62 apply when the player hits E key while holding an object.
In this case, objectInHand is released by setting its parent to null , so it is not a child of the
holder anymore. Finally, it is necessary to set the value of objectInHand to null , in order
to free the space for holding another object in the future. The final result can be seen in
scene11 in the accompanying project.
Search WWH ::




Custom Search