Weird collision detection between player and ground
I am currently working on a 3d version of games like Gravity Guy. So basically a jump and run where you automatically move forward and change the gravity instead of jumping. You can only use the "jump" again if you collide with the ground and have finished turning by 180°. This works perfectly in my game, as long as the player doesn't hit a none "ground" Object. After that the player sometimes rapidly enters and exits the ground collider, which makes the game unplayable. This seems to happen more often if the obstacle he hits is moving. The player has a rigidbody attached to it. My code for the gravity change looks Like this:
if (OnGround && Input.GetKeyDown (KeyCode.Space)) {
ChangeGrav ();
audi.PlayOneShot(JumpClip);
}
}
public void ChangeGrav(){
Up = !Up;
GameMangerScript.instance.grav = -GameMangerScript.instance.grav;
OnGround = false;
}
void OnCollisionExit(Collision other){
if (other.transform.tag == "Ground"){
OnGround = false;
playedsound = false;
Debug.Log("exit ground");
}
}
void OnCollisionEnter(Collision other)
{
if (rotZ == 0 || rotZ == 180)//player gameobject has to finish turning
{
if (other.transform.tag == "Ground" && !playedsound)
{
OnGround = true;
audi.PlayOneShot(TouchGroundClip);
playedsound = true;
Debug.Log("enter ground");
}
}
}
And my Movement currently looks like this:
void FixedUpdate()
{
h = Input.GetAxis("Horizontal") * (HorizontalControl+(Thrust/ControlCange));
v = Input.GetAxis("Vertical") * (VerticalControl+ (Thrust/ControlCange));
gameObject.transform.position+= (transform.forward *v + transform.right * h + ThrustDir * (Thrust + DecreasingThrust)) * Time.deltaTime;
Originally i used Rigidbody.MovePosition(), but that didn't work either. I just can't figure whats wrong. Can anyone help me out?
Answer by particlesmash · Nov 27, 2018 at 09:56 AM
Instead of using the OnCollisionEnter and OnCollisionExit functions for detecting when the player is on the ground, I would use a ray cast with a layer mask. That way it is much more consistent which should fix your problem of exiting and entering multiple times.