Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

can someone explain this line of code involving the raycasts in the ground detection system? That entire section is barely making any sense to me and there's barely any explanation in the guide. 

onGround = Physics2D.Raycast(transform.position + colliderOffset, Vector2.down, groundLength, groundLayer) || Physics2D.Raycast(transform.position - colliderOffset, Vector2.down, groundLength, groundLayer);

Thanks :D

(+1)

This code is looking below the character to see if there is anything identified as "ground" close enough to the character.

The Raycast function looks like this:

RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask)

The function will shoot a ray in the specified direction and return information about any objects that the ray hits.

In this case, the ray begins at transform.position + colliderOffset and is directed downward (Vector2.down). 

The ray extends a distance of groundLength (which is probably based on the size of the character). If this is too large, then onGround would return true before you land. If it is too small, then the rays may not reach the edge of the collider and won't detect the ground even if the character is standing on it.

The LayerMask groundLayer identifies which physics layers should be considered as "ground". The ray will ignore other layers.

If the ray doesn't hit anything, then Raycast will return null which is interpreted as "false" when used as a bool. If the ray hits something, it returns a valid RayCastHit2D object with additional information about the collision. But in this case we only care whether or not there was a hit, so a valid object is interpreted as "true" for the onGround bool.

There are two raycasts, one with origin transform.position - colliderOffset and one with origin transform.position + colliderOffset. I expect that this is to cast rays starting from the left edge and right edge of the object so that you detect ground even if you are partially hanging off of a ledge.