Game Development Reference
In-Depth Information
In our code, we use the
Input.GetButton("Horizontal")
funcion.
GetButton
means
we are checking if the
Horizontal
buton is being held down. The
Horizontal
is the
name of the irst input buton, as we can see in the preceding screenshot. We can also use
Input.GetKey("left")
to control our character. It will have the same result with
Input.
GetButton
, but the difference is
GetKey
will only detect the specific key in our code. It
isn't lexible for the user to adjust the key coniguraion during the game play. The
Negative
Button
and
Positive Button
here will send the negaive and posiive
value, which in most
cases is used for controlling direcion such as let, right, up, and down. There is a
Dead
parameter, which will set any number that is lower than this parameter to
0
, which is very
useful when we use a joysick. Also, seing the
Type
to
key/mouse
button
and enabling the
Snap
parameter will reset axis values to zero after it receives opposite inputs.
Jumping and physics
Now, we are making our character jump by using
Physics.Raycast
in Unity. We can also
use the
OnCollisionEnter
,
OnCollisionExit
, or
OnCollisionStay
funcions to
check the collision detecion between our character and the loor, but in this case we will use
Raycast
because it's more flexible to adjust.
However, because the
Raycast
is only a line with no thickness, there is a chance that if
we have a very thin plaform, the
Raycast
can miss it. And it will cause the problem that
we might not be able to jump. So, we should make sure that the plaform should have the
thickness of least 0.1 units.
Engage Thrusters
Coninuing from the last step, let's get on with it as follows:
1. Let's open our
CharacterController_2D.js
file and add this code to it; first
our parameters:
private var b_isJumping : boolean;
private var f_height : float;
private var f_lastY : float;
public var jumpSprite : JumpSpriteManager;
public var layerMask : LayerMask; //to check for the raycast
2. Then, we go to the
public function Start ()
funcion and add the following
code inside this funcion:
//Get mesh from the character MeshFilter
mesh = GetComponent(MeshFilter).sharedMesh;
//Get hight from the top of our character to the bottom of our
box collider
f_height = mesh.bounds.size.y* transform.localScale.y;