Game Development Reference
In-Depth Information
Rather than assign explicit coordinates to
platformStartPosition
with the variable declaration,
your script assigns whatever the position of the platform game object is in the
Start()
function.
By writing it this way, you can reposition the platform in the Scene view without having to come back
and edit the script to update the start position coordinates.
(2) private var platformEndPosition : Vector3;
public var lowLevel : float = 6;
function Start () {
...
platformEndPosition = (transform.position - Vector3(0,
lowLevel, 0));
}
In the same fashion, the
platformEndPosition
variable is declared but not assigned explicit
coordinates. The platform will move straight down along the Y-axis for the distance designated
by the
lowLevel
variable. A value of 6 is explicitly assigned to
lowLevel
to begin with, but more
importantly the
lowLevel
variable is public so you can adjust the range of the platform's movement
directly in the editor. The
platformEndPosition
is assigned in the
Start()
function the result of
subtracting the
lowLevel
value from the y coordinate of the
platformStartPosition
.
(3) public var duration : float = 5.0f;
The
duration
variable determines how fast the platform moves from
platformStartPosition
to
platformEndPosition
, so making it public allows you to adjust the speed of the platform movement
directly from the editor.
(4) private var step : float = 0.0f;
private var movingBack : boolean = false;
Both
step
and
movingBack
are used for changing the direction of the platform to maintain a repeating
up-and-down movement during gameplay.
(5) function FixedUpdate() {
Since this is physics-based rigidbody movement, the
FixedUpdate()
function is used instead of
Update()
. A common beginner mistake is to forget the Rigidbody component for the game object.
Make sure the Platform 4 × 1 × 4 has a Rigidbody component. If not, select it in the Hierarchy, then
in the Inspector select Add Component ➤ Physics ➤ Rigidbody. When the Rigidbody component
appears in the Inspector, uncheck Use Gravity since this isn't needed and check Is Kinematic so the
platform movement is unaffected by the player character jumping onto it.
(6) var delta : float = (Time.deltaTime / duration);
Time.deltaTime
is the time in seconds it took to complete the last frame, so dividing by
duration
assigns a normalized fraction to
delta
so that
(7) if(movingBack) step -= delta;