I need to check when my character is grounded so that i wouldn't continue to play the walk sound when he falls off something (or jumps in the air).
This is the code that takes care of the jumping, falling and gravity. cc in this code block is the CharacterController component. If the character already is grounded and the jump key was not pressed, the vertical speed will remain zero; if he is not grounded, then gravity is applied in the y direction.
if (cc.isGrounded) {
grounded = true;
if (Input.GetButton ("Jump") == true) {
ySpeed = jumpSpeed;
jumpSound.audio.Play();
} else {
ySpeed = 0;
}
} else {
grounded = false;
ySpeed += Physics.gravity.y * Time.deltaTime;
}
Debug.Log (cc.isGrounded == true ? "yes" : "no");
The problem is that the isGrounded value constantly fluctuates, and the Debug.Log line fluctuates between yes and no, so when I use the isGrounded condition for playing the footsteps sound, the sound randomly stops and starts again, even though I am constantly just walking straight on a simple smooth plane.
Is there a way around this?
I am not concerned about the fact that isGrounded is fluctuating and that it's incorrect, because in gameplay that is not noticable. I am only worried about how to constantly play the footsteps sound while the character is walking, and not jumping, and not falling. As far as my concerns go, this may be solved by actually fixing the fluctuation or another workaround; I would be happy with either.
These are my conditions for playing the footsteps sound:
if((Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0) && grounded == true) {
if(this.audio.isPlaying != true) {
this.audio.Play ();
}
} else if (this.audio.isPlaying) {
this.audio.Stop ();
}