- Home /
Jumping Problem?
I am using GetMouseButtonDown to allow a sphere in my game to jump. The problem is, you are able to jump multiple times right in a row and pretty much fly. What is the simplest way to only allow the player to only jump once at a time?
Answer by robertbu · Aug 26, 2013 at 03:42 AM
The typical way is to only allow a character to jump if it is grounded. How you detect ground will depend on your game. You can:
You can pick a certain height and call grounded anything that has a 'y' value less than the specified height.
You can do a Physics.Raycast() down and detect the distance to the surface. Under some threshold, and you are grounded.
You can detect a collision and either based on the type of collision or based on the contact points say something is grounded. See OnCollisionEnter().
Assuming your jump runs in a fixed amount time, another solution is to lock the user out from jumping for the time of the jump.
Answer by Ozzyel-PT · Aug 26, 2013 at 04:14 AM
If you're using a Character Controller, make a condition if it's grounded.
private var ableToJump = true;
function Start () {
controller = GetComponent(CharacterController);
}
function Update (){
if (controller.isGrounded)
ableToJump = true;
//move y dierction command....
}else{
ableToJump = false;
}
}
Hope it helps.
Answer by pickle chips · Aug 26, 2013 at 03:48 AM
If there is a character controller attached to the sphere, you could use the CharacterController.IsGrounded property to check whether the sphere is back on the ground.
Otherwise, you could use a float variable, to time how long it takes until you can jump again, which is very simple - but not the best way, Using code such as this:
float timeAfterClicked; //How long has it been since they last clicked?
float timeToJump //The cooldown of how long you want it to be until they can jump again
void Update() {
if (Input.GetMouseButtonDown(0) && timeAfterClicked >= 0) {
Jump(); //Whatever code you use to jump
timeAfterClicked += timeToJump;
}
if (timeAfterClicked > 0) {
timeAfterClicked -= Time.deltatime;
}
}
This will time how long it's taken since your last jump, and after the cooldown time (timeToJump) has passed, you will be able to jump again.
Your answer
Follow this Question
Related Questions
Bullets sometimes flying through enemies in Unity2D 2 Answers
Allow users to input a list? 0 Answers
If Grounded 2 Answers
AddForce to sphere 1 Answer
unity2d javascript jump help 1 Answer