Game Development Reference
In-Depth Information
Before discussing the details of this script, notice
RequireComponent
annotation we used
before declaring the class. This annotation requires the game object to which
SlidingDoor
script is attached to have a
GeneralDoor
script as well. If you attach
SlidingDoor
script
to an object, Unity automatically attaches
GeneralDoor
script if does not exist. Similarly,
if you try to remove
GeneralDoor
script from an object while
SlidingDoor
is attached to
it, the removal is refused by Unity. We benefit from this mechanism because
SlidingDoor
completely depends on
GeneralDoor
and cannot be used alone.
Th
slidingDirection
vector determines the distance the door moves along its local axes when
it is opened. For example, if the sliding direction is (0, 2, 0), the door is going to move two
meters up when it is opened. The variable
speed
controls the speed of the door when it opens
or closes. Opening and closing the door is in fact a process of smoothly moving it between
originalPosition
and
slidingPosition
. The initial position of the door when
Start()
is called is
taken as
originalPosition
(close position). On the other hand,
slidingPosition
(open position) is
computed by adding
slidingDirection
to
originalPosition
. In addition to
door
which refer-
ences the attached
GeneralDoor
, we implement an internal state management by using the
enumerator
SlidingDoorState
(line 107). The variable
state
of type
SlidingDoorState
tells us
what the sliding door is doing at any given moment (opened, closed, opening, or closing).
The initial state is set according to
door. initallyOpen
. Illustration 80 shows a double sliding
door that has two parts with opposite sliding directions.