I need to detect if the player is on the ground… Currently im using this
Physics.Raycast(transform.position, -transform.up, out hit, yBounds + 0.03f);
which does its job, however it only calculates from the y axis, which if the player is even slightly off center, or theres a crack in the ground, the player’s gravity starts pulling him down causing very strange behavior.
I attempted calculating from 5 axis using this:
RaycastHit hit;
Physics.Raycast(transform.position, -transform.up, out hit, yBounds + 0.03f);
if(hit.transform != null){
Debug.Log(hit.transform.name + " On Gound");
return true;
}else{
RaycastHit[] hits = new RaycastHit[4];
Vector3[] check = {getBounds(xBounds, 0, 0), getBounds(-xBounds, 0, 0), getBounds(0, 0, zBounds), getBounds(0, 0, -zBounds)};
for(int i = 0; i < 4; i++){
Physics.Raycast(check_, -transform.up, out hits*, yBounds + 0.03f);*_
_ if(hits*.transform != null){
Debug.Log(hits.transform.name + " On Gound");
return true;
}
}
Debug.Log(“OFF - Gound”);
return false;
}RaycastHit hit;
Physics.Raycast(transform.position, -transform.up, out hit, yBounds + 0.03f);
if(hit.transform != null){
Debug.Log(hit.transform.name + " On Gound");
return true;
}else{
RaycastHit hits = new RaycastHit[4];
Vector3 check = {getBounds(xBounds, 0, 0), getBounds(-xBounds, 0, 0), getBounds(0, 0, zBounds), getBounds(0, 0, -zBounds)};
for(int i = 0; i < 4; i++){
Physics.Raycast(check, -transform.up, out hits, yBounds + 0.03f);
if(hits.transform != null){
Debug.Log(hits.transform.name + " On Gound");
return true;
}
}
Debug.Log(“OFF - Gound”);
return false;
}
(the getGounds method just returns a vector of the player’s position relative to its collider extents:
public Vector3 getBounds(float x, float y, float z){
return new Vector3(transform.position.x + x, transform.position.y + y, transform.position.z + z);
}
)*
While this works when the player is not rotated, but once the player is rotated the collider extents are no longer accurate - and in my game the player is constantly being rotated in many directions.
I have no clue what to do, because raycasting beneath the player in this manner is very important to other features of my game. Please help. Can someone also advise me as to whether or not the way I’m doing it now is efficient at all? Would this hurt performance if I did something similar to this?_