Game Development Reference
In-Depth Information
Since we are going to replace this object with a number of pieces when broken, we
need to provide the prefabs of these pieces in pieces array. The variable pieceCopies specifies
how many times each piece prefab must be generated. For example if we have two prefabs
andset pieceCopies to 5, we end up with a total of 10 pieces when the object is broken. ex-
plosionPower determines how strong is the generated explosion when this object brakes.
This explosion is going to be used only to spread the pieces after destruction, and have no
effect on other objects near the breakable. Finally, we can set a time after which remove
the pieces from the scene using pieceLifeTime . If the value of this variable is zero or less,
the pieces are going to be permanent.
We call Break() function once whenever we want to break the object. This functions does
three jobs: generates the pieces, inform other scripts that breaking has happened by sending
OnBreak message, and finally destroys the object. The interesting part are the two nested
foreach and for loops. The outer loops iterates over all prefabs in pieces array, and the
second one iterates pieceCopies times, in order to instantiate the required number of objects
from each prefab. The position where each piece is instantiated is random, but it must fall
within the borders of the original object. These borders are determined using the local scale
of the object. After moving the piece to its randomly generated position, we apply the ex-
plosion force to it. Keep in mind that the explosion is positioned at the center of the original
object. As a result, all pieces will be pushed away from the center by the explosion force.
When the piece is ready, we check whether pieceLifeTime is greater than zero, and even-
tually destroy the piece after the specified time. Once all pieces are generated, we send
OnBreak message to inform other scripts that the object has been broken, and then destroy
the original object.
To activate these breakable windows in the building we made in scene19 , we must add a
script that works as a bridge between Destructible and Breakable scripts. This script must
be added to breakable objects in order to send Break message when OnDestruction message
is received. The script BreakOnDestruct is shown in Listing 60. The complete building with
destructibles and breakables is in scene19 in the accompanying project.
Search WWH ::




Custom Search