Game Development Reference
In-Depth Information
The script starts by giving the rigid body of the rocket a force with enough magnitude to
launch it. After that it starts to compute the life time of the rocket as set in the inspector.
However, if the rocket hits an object during its movement, it destroys immediately after
sending
OnRocketHit
other scripts and providing a reference to the colliding object. Notice
that we count for the case of multiple collisions, and hence use the internal
destroyed
flag.
By doing this, we guarantee that
OnRocketHit
is sent only once. After hitting the target, the
rocket must explode into pieces. For this purpose, we can reuse
Breakable
script (Listing
59 page 150) with a custom piece prefab. However, we need to set a high value, such as
1000, for
explosionPower
variable. The reason for that is the fact that the rocket does not
simply
break
, but rather
explode
. This means that its pieces must be scattered appropriately
to mimic an explosion, which needs a force with high magnitude.
To break the rocket upon collision with another object (the target), we need a third script
to link
RPGRocket
and
Breakable
. The script has to receive
OnRocketHit
message and
eventually send
Break
message to the breakable. This script is
BreakOnRocketHit
shown in
Listing 89. This is a straightforward script that does nothing other than receiving a message
and sends another one.