- Home /
Character Fails To Jump Sometimes
So I have a jump button in my game that depends on two booleans, canJump and isJumping. For the most part the code works the way I want it to with a problem that for some reason it just fails to work unless I double tap it and sometimes I just have to wait an arbitrary amount of time in order to jump but I have no idea why.
private float origjump;
private bool isJumping = false;
private bool canJump = true;
void singleJump(){
if (Input.GetButtonDown ("Jump") && !isJumping && canJump) {
origjump = transform.position.y;
constantForce.relativeForce = new Vector3(0,jumpForce,0);
isJumping = true;
canJump = false;
}
else constantForce.relativeForce = new Vector3 (0,-9.8f,0);
if (Input.GetButtonUp ("Jump")) {
canJump = false;
}
if (transform.position.y > origjump + 0.1f && isJumping) {
constantForce.relativeForce = new Vector3 (0,-9.8f,0);
}
}
void OnTriggerStay(Collider other){
constantForce.relativeForce = new Vector3 (0,-9.8f,0);
canJump = true;
isJumping = false;
}
This is the relevant code. So on the OnTriggerStay method, It's basically just checking to make sure that the player hit the ground and resets the bools so they can jump again, and the singleJump method is the Jump Method that checks those bools and jumps. Pretty much any frame the object is touching the floor it should be able to jump but it doesn't, can anyone help me with this?
Answer by Stygtand · Jun 06, 2014 at 08:48 AM
http://docs.unity3d.com/ScriptReference/Collider.OnTriggerStay.html
OnTriggerStay function is on the physics timer so it wont necessary run every frame.
You need to find a way to trigger isGrounded.
you could solve it with something like this:
bool isgrounded = true;
void Update()
{
if(isgrounded == true)
{
//Do your action Here...
}
}
//make sure u replace "floor" with your gameobject name.on which player is standing
void OnCollisionEnter(Collision theCollision){
if(theCollision.gameObject.name == "floor")
{
isgrounded = true;
}
}
//consider when character is jumping .. it will exit collision.
void OnCollisionExit(Collision theCollision){
if(theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
Wouldn't using OnCollision like this give the player the ability to jump even when touching a wall?
Your answer
Follow this Question
Related Questions
Can't figure out how to detect ground (2D) 1 Answer
Get child tag from parent-child collision 1 Answer
Delay Jumping 3 Answers
Box collider didn't jump with player 1 Answer