Game Development Reference
In-Depth Information
era.main to get access to the Main Camera object and set its position relative to Play-
er .
Tip
Camera.main lets us access a Camera object that has the MainCamera tag from any-
where we want.
In the FixedUpdate() function, we change the animation state from Idle to Walk by
using _animator.SetFloat("Speed",
Mathf.Abs(_horizontalInput)); . Next, we get the x speed and check that the
speed is lower than the maximum speed. Then, we add the force to Rigidbody2D by us-
ing rigidbody2D.AddForce(Vector2.right * _horizontalInput *
moveForce); . We also make sure that the velocity doesn't reach the maximum limit
after adding the force by assigning newVelocity to rigidbody2D.velocity .
Next, we trigger the jump animation state by using _animat-
or.SetTrigger("Jump"); . We also add the force to make our character jump using
rigidbody2D.AddForce(new Vector2(Of,jumpForce); . Then, we trigger
the fall animation state by using _animator.SetTrigger("Fall"); . We also trig-
ger the ground animation state by using _animator.SetTrigger("Ground"); if
our character is falling.
Then, we check for the current animation state by getting animatorStateInfo using
_animator.GetCurrentAnimatorStateInfo(0); . Then, if the current state is
the jump state and y velocity lower than 0 , we will change the animation state to the fall
state using if ((rigidbody2D.velocity.y < 0) && (anima-
tionStateInfo.IsName("BaseLayer.Jump")) .
At last, we use the OnDrawGizmos() function to see the visual of the ray that was
drawn in the Grounded() function using Physics2D.Raycast . We can also use
this function to debug the game without removing any code when releasing the game. Be-
cause all the code in the OnDrawGizmos() function won't be shown in the real game,
it's a convenient way to debug our game. As we can see from the following figure, the red
arrows represent where the raycast is, which will only show in the scene view:
Search WWH ::




Custom Search