Game Development Reference
In-Depth Information
Then, we used the
Input
class to detect when the player presses a key on the keyboard.
We do all the character control in the
update()
funcion. First, we use
if (Input.
GetButton("Horizontal")) { }
to check if the player pressed a
Horizontal
key,
(for which the default in Unity is
A, D
, left arrow, or right arrow key), and we move our
character if he/she did. The first line in this
if
statement checks the direcion, which we
are using,
in_direction =Input.GetAxis("Horizontal") < 0 ? -1: 1;
, which
means that if the player presses a
Horizontal
key, we will get the axis number from the
Input.GetAxis("Horizontal")
funcion. The
Input.GetAxis
funcion will return
the range from -1 to 1 depending on the pressure of the player pressing. Then, we check if
the number is lower than 0 or not, if it's then the funcion returns -1 (move to let), if not it
returns 1 (move to right). Then in the line
rigidbody.velocity = new Vector3((in_
direction*f_speed), rigidbody.velocity.y, 0);
,we applied the direcion and
speed to the
rigidbody
velocity. We don't apply any velocity in the Z-axis because we are
not moving our character in that direcion.
Lastly, we included the
SpriteManager
class in our
CharacterController_2D.js
ile
to control our sprite texture to play loop animaion by using the maximum of frame we
had calculated with the ime to play each frame. Let's take a look at our
SpriteManager
class.
spriteTexture
is basically a set of sprite texture that get held in this class. This
textures will get a call and apply to the main material texture when the character is changing
their movement, such as from walk to stay, stay to walk, or walk to jump, and so on.
in_
framePerSec
is the total frames of the sprite texture, which will be used to calculate when
the next frame will be showed.
in_gridX
is the number of the row in our sprite texture,
and
in_gridY
is the number of the column in our sprite texture, which will be used to
calculate the
Tiling
and
Offset
of the texture that we have already seen in the last step. We
also have private parameters
f_timePercent
,
f_nextTime
,
f_gridX
,
f_gridY
, and
in_curFrame
, which are used to calculate in the
updateAnimation()
funcion. Next, we
have the
init()
funcion. This funcion is basically for seing up our parameters. Then, the
updateAnimation()
funcion will get the material and direcion from our main character
to calculate and update our sprite animaion. Lastly, we have a
resetFrame()
funcion to
reset our animaion frame back to one.