Hello, I’m fairly new to scripting and I’m having an issue with grounding my 2D player. I’m drawing a raycast down to tell if I’m grounded, The ray starts 3.13 from the ground. When I put distance to anything less then 3.13 is says I’m not grounded, but anything equal or higher then 3.13, works, but I can double jump and after the second jump, then grounded is turned off. I thought I wrote the code to say that a ray less then 3.13 in distance will be considered grounded, but it is not working for some reason. Any help with this will be greatly appreciated or a simpler code would also be great. I feel like this should be easier then what I’m doing. I got this from a tutorial that was older. Thanks!
public bool isGrounded;
public float distance = 3.13f;
Whenever I am having trouble telling what code is doing I either track it down with stepping through code, Logging variables, or drawing gizmos. With raycasting I suggest you check out drawing gizmos at the start of the ray and where it collides to give you a visual sense of what its doing. It would look something like this:
void OnDrawGizmos() {
//Start of ray
Gizmos.color = Color.red;
Gizmos.DrawSphere(rayStartPosition, .02f);
//Rays line
Gizmos.color = Color.blue;
Gizmos.DrawRay(ray);
//Rays hit position
Gizmos.color = Color.green;
Gizmos.DrawSphere(rayHitPosition, .01f);
}
And you would have to create 3 variables and set them whenever you do the raycast.
For this specific case, what is the pivot point of the GameObject that this script is attached to? If it is the bottom of the player (which i suggest) you can do a very small raycast like .01f to see if you are on the ground.
Also, I suggest putting the distance as the third parameter to your Raycast function. Then you don’t need to check the distance in the if statement and it should be more optimized.
Lastly, something I have come across before is the raycast will hit a collider that is one my player. So make sure your ray isn’t hitting things it shouldn’t either by using a layermask or if you just want to rule it out, turn off your players colliders while in play mode and turn off its gravity.