- Home /
How can I only play a audio source when the player is on the ground and pressed space?
Here's my code:
var isGrounded : boolean=false;
function Update()
{
if(Input.GetKeyDown("space") && isGrounded)
{
audio.Play();
}
isGrounded=false;
}
function OnCollisionEnter(collisionInfo : Collision) {
//we are on something
isGrounded=true;
}
The problem is, when I am on the ground it wont set isGrounded as true. How can I fix this?
Answer by aldonaletto · Jun 21, 2012 at 12:32 PM
If your character is a CharacterController, you can use its builtin property isGrounded:
if (GetComponent(CharacterController).isGrounded && Input.GetKeyDown("space")){
...
If the character is a rigidbody or a simple object, it's better to use another approach: do a raycast downwards with suitable length - if something is hit, the character is grounded:
isGrounded = Physics.Raycast(transform.position, Vector3.down, len);
where len is the length - you can set it manually, or at Start with something like this:
var len: float; // distance from character's pivot to ground
function Start(){
len = collider.bounds.extents.y+0.2;
}
This code calculates the distance from the character center (where the pivot usually is) to the ground and adds 0.2 to give a margin for inclined terrain - this margin is an arbitrary value, and you may want to increase it to detect ground at steeper places.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073050im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Changing the audio on key press! Help 3 Answers
Enter spoken words in game 1 Answer
Sound on collision 3 Answers