Just "jumping" is easier than I thought.
if (Input.GetButtonDown("Jump"))
{
rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
}
rigid.Addforce
.Vector2.up
and multiply by the number of jumpPower
.Pseudo Code:
If the player is touching the ground and pressing jump button, the player can jump.
If the player is not touching the ground, the player can't jump.
Physics2D.Boxcast()
to check if the player is on the ground or not.
Physics.Boxcast()
creates a box-shaped volume and detects collision, which returns a boolean value.
Boxcast Parameters:
Physics2D.Boxcast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask)
We need to make variables that will go into the Boxcast parameters.
public bool IsGround()
{
if (Physics2D.BoxCast(transform.position, boxSize, 0, -transform.up, distance, groundLayer))
{
return true;
}
else
{
return false;
}
}
We will make a new bool called IsGround()
so we can use it to check if the player is on the ground.
We can plug our variables into the Boxcast parameters.
I don't want any angles so I put 0 as a angle value.
I want to check what's under our player, so I did -transform.up
.
There's no
transform.left
ortransform.down
in transform components.
Since it's a boolean, we'll return true
if our Boxcast is detecting the ground, and return false
if it's not detecting any ground.
Boxcast is not visible by default, so it's difficult to control it.
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position - transform.up * distance, boxsize);
}
We'll use void OnDrawGizmos()
.
void OnDrawGizmos()
is a tool that draws the visual represent for the gizmos. It's primarily used to debug or visual purposes.
We can use Gizmos.DrawWireCube
to visualize our Boxcast.
Gizmos.DrawWireCube
draws wired cube to visualize the box.
Use (transform.position - transform.up * distance, boxsize);
We want our center for the box to be same as Boxcast, which is why we did
transform.position - transform.up
. Then, we multiply it by thedistance
value to control the boxcast's y-axis location.
Now we can make a Layer called "Ground" to detect the ground.
void Jump()
and call it in Update()
to jump. void Jump()
{
if (Input.GetButtonDown("Jump") && IsGround())
{
rigid.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
}
}
void Jump()
in the Update()
and selected the groundLayer in the player's script.