In the game, character jumping is a normal and common ability. But with such a seemingly simple function, many problems will be encountered in the implementation process.
In this article, I will share three ways of ground detection.
project address
Why ground inspection?
in the game. The user can operate the character in the air and the character on the ground in different ways.
For example, different attack methods in the air and on the ground, you can squat on the ground, double jump in the air, fail to touch the ground, and so on.
Therefore, to achieve this difference, we must first know the current spatial position of the character, so ground detection is a must.
X-ray inspection
Core idea:
A ray is emitted downward from the bottom of the character, and when it touches the ground, the character is considered to be on the ground.
code show as below:
void Update()
{
// TODO 避免检测太频繁影响性能,可以增大检测间隔时间
var raycastAll = Physics2D.RaycastAll(transform.position, Vector2.down, 0.1f, layerMask);
if (raycastAll.Length > 0)
{
// 在地面
isGrounded = true;
}
else
{
// 离地
isGrounded = false;
}
}
However, there are problems with this reality.
When the character is on the edge of the ground or on a slope, a single ray will not be able to detect the ground, resulting in a wrong judgment.
To solve this problem is also very simple, we can add a few more rays, that's fine.
But this is a bit cumbersome to implement. Is there a more convenient way?
collider
Core idea:
Using the collision body provided by the Unity engine, we can monitor the collision function to complete the ground detection logic.
code show as below:
void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag("Ground"))
{
// 在地面
isGrounded = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
// 离地
isGrounded = false;
}
By adjusting the size of the collider, we can already meet our daily development needs.
If you don't want to add multiple colliders, try the ray box below.
ray box
Core idea:
It also uses ray detection, but changes from multiple rays to ray boxes. From line to surface.
code show as below:
void Update()
{
var raycastAll = Physics2D.OverlapBoxAll(transform.position, new Vector2(0.4f,0.4f), 0,layerMask);
if (raycastAll.Length > 0)
{
// 在地面
isGrounded = true;
}
else
{
// 离地
isGrounded = false;
}
}
The above is the content of this article. If you think it's not bad, you can like and pay attention~