Game Development Reference
In-Depth Information
The third speed is the horizontal speed defined by movementSpeed variable, which is the
speed of the character horizontal movement towards left and right. When we combine these
three speeds together, they give us a resultant velocity that has two components on x and y
axes. That's why we define speed , which is a variable of type Vector2 (a two dimensional
vector), in order to store the values of these two components and use them in each update
iteration. We need to keep the value of the velocity stored between the frames, which is spe-
cially important for the vertical speed. The vertical speed changes during the time between
the frames, and hence we keep its value to be able to update the next frame correctly.
The first step in Update() function, which lies between lines 26 and 32, is known to us.
It simply reads keyboard input and interprets it as horizontal movement. As you can see,
the right arrow gives us the positive value of movementSpeed , while left arrow gives us the
negative value of the same variable. If the player is not pressing any of these keys, we set the
value of x member of speed to zero. We use the member x of speed variable to keep hori-
zontal speed value to use it later for final displacement of the object.
The second step in update (lines 35 through 40) is to read the space bar and implement the
jumping if possible. Notice here that we use GetKeyDown() in order to prevent consecutive
jumping by keeping the space bar down, and force the player to release space and press it
again to re-jump. Additionally, we do not allow the character to jump unless it is standing
on the ground at the moment the player presses space. In our scene, the original y position
of the character is 0.5, so we take it as the ground reference to determine whether or not
the character is grounded. Once we make sure that the character is grounded, we change y
member of speed to the value of jumpSpeed .
The third step is in lines 43 through 45, in which we perform the actual displacement of
the object based on the values of speed we have computed in the previous steps. We use
transform.Translate() to perform displacement based on the values stored in speed . The
displacement takes place on x and y axes, and we multiply by Time.deltaTime as usual, to
work out the distance from the speed values we have.
After moving the object, we have one step remaining. This step is to compute the new ver-
tical speed of the object. As described earlier, the y value of 0.5 in the character position
means that the character is standing on the ground. If this is not the case (lines 48 through
50), it means that the character is currently in the air; which requires us to reduce its vertic-
Search WWH ::




Custom Search