First of all, I’m terribly sorry if this is in the wrong section, I didn’t know if the 2D section was only for resources and such and not for scripting.
I’m making a small platform with weird stuff like changing gravity and such, and I’m wondering what the best method for checking if a player is grounded, is. I know of the onCollisionEnter and the linecast method, but I was wondering if there was any other method better suited? A javascript snippet with a standard if/else that sets the grounded variable, would be greatly appreciated, whatever the best method is. Thank you very much.
void OnCollisionStay()
{
Vector3 myPos = _pgController.MyTrans.position;
Vector3 myScale = _pgController.MyTrans.localScale;
RaycastHit groundInfo;
_isHittingObject = true;
//This is an additional check to see if we are "grounded" actually at the feet.. and not from the side.
if (Physics.Raycast(myPos + rightLeg, -_pgController.MyTrans.up, out groundInfo, myScale.y * checkDistance, ~(int)LayerEnums.Player) ||
Physics.Raycast(myPos + leftLeg, -_pgController.MyTrans.up, out groundInfo, myScale.y * checkDistance, ~(int)LayerEnums.Player))
{
_pgController.IsGrounded = true;
}
else
{
_pgController.IsGrounded = false;
}
}
I use the _isHittingObject because I want to allow the player to continue to move while in the air. If you don’t care about in air control don’t worry about it. Otherwise you can just add in a simple check like this:
if (!_isHittingObject !_pgController.IsGrounded || _isHittingObject _pgController.IsGrounded)
targetVelocity = new Vector3(1, 0, 1);
The difference between his and mine is I never set it back to false manually. His might be more efficient but its hard to know.
Honestly, this doesn’t seem very performance optimized. I might be wrong, but I would think this method took up way for resources than most other methods.