I'm making a game revolving around moving a ball around a space. My game has a jump mechanic, so I need to know when I'm grounded in order to determine when I'm able to jump. Best way to check this is to setup raycast from ball's origin and make it constantly face downwards. However, I'm running into an embarrassing issue: the ball keeps rotating, so I'm not able to find a constant downward ray to use for finding the ground.
I started making code that looks similar to this, which the object's local transform:
bool grounded = false;
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
//determine if object is on ground
grounded = true;
}
This caused the issue I stated earlier, where the ray would point downward but only relative to the object's current rotation. In other words, if the ball was upside-down, the ray would be pointing upwards.
My current code for this look similar to this, which now uses world space to determine what is 'down':
bool grounded = false;
Ray ray = new Ray(transform.position, -Vector3.up);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
//determine if object is on ground
grounded = true;
}
However, in this instance, the ball raycast actually points directly to position Vector3(0,-1,0), which is even weirder than my initial problem and shouldn't be an issue based on other posts about this issue.
The only other way I can think of to properly determine whether the object is grounded is to see if it collides with anything. However, the other reasons I want to determine whether the player is grounded using raycast are:
- for determining whether the player is over an endless pit (e.g. if they fell off the world) in order to start a kill/respawn timer
- to ensure the player can perform a move equivalent to a butt stomp while in the air
If anyone knows how to perform a raycast on a spherical object in Unity, it's be much appreciated.