- Home /
Checking if grounded using SphereCast -- Acting like Raycast
So I've been trying to convert my old Physics.Raycast grounding check to a Physics.spherecast for the sake of being more lenient with what is considered "grounded" in my game. Unfortunately my new spherecast check is working exactly the same as my old Raycast check and is causing this problem below:
Basically, the issue is that my game requires the player to be grounded in order to perform a jump (which is pretty standard) and uses the IsGrounded function to detect if the player is on the ground. The function looks like this:
public bool IsGrounded()
{
RaycastHit rayHit;
float characterHeight = GetComponent<BoxCollider> ().size.y;
float characterWidth = GetComponent<BoxCollider> ().size.x;
Vector3 startPoint = transform.position;
return Physics.SphereCast (startPoint, characterWidth/2, Vector3.down, out rayHit, characterHeight / 2);
}
The issue is that I want the player to be considered grounded even when he/she is barely hanging off the edge as the image above to allow for precise jump timing and to make sure that there's no chance of the player's jump request to be ignored because the pawn class' internal physics state is set to airborne.
Maybe I'm doing this entirely the wrong way, but it seemed like a SphereCast would be the ideal solution to having a volumetric raycast / quick collision detection. I could also do multiple raycasts, but that probably wouldn't be optimized. Any reason why this current method isn't work or what else I should try to get it working?
You should take a look at how isGrounded works in the character controller standard asset. I'm not certain but I think they use OnCollisionEnter() and check if the y value of the collision points is < 0 (meaning that the player is colliding with something below its centre, you might change 0 to < 0.9 depending on the size of your collider) if a collision point matches the less-than then they set isGrounded to true, then set it to false in OnCollisionExit()
Scribe
Answer by whydoidoit · Feb 12, 2014 at 11:28 AM
Sphere casting might be more expensive compared to multiple ray casts - especially as multiple casts can cease as soon as any of them finds the ground. You should really be caching that BoxCollider GetComponent call too - indeed presuming the size doesn't change you could just cache that in Start.
I'm unsure of why your sphere cast isn't working unless it's something to do with getting the wrong distance etc (is your model's position in the centre? It appears to be, in which case the sphere will be very narrow when it reaches the ground if you are casting exactly that far).
Your answer
Follow this Question
Related Questions
Spherecast for ground check glitch 1 Answer
SphereCastAll sees for miles 2 Answers
Physics.SphereCast to detect things below my character? 0 Answers
Why won't my spherecast work? 0 Answers