Hello everyone. I’m having trouble with making my character jump. I can make him jump but the height of that jump is inconsistent. I don’t want him to jump very high, but sometimes he just rockets up into the air, and I don’t know what is causing it. Here’s my code. I took out everything except what related to jumping.
public int jumpSpeed; //Jump speed.
private bool canJump; //Whether the player can jump or not.
private Rigidbody rb; //Gives access to the rigidbody.
void Start(){ //Specifies the Rigidody.
rb = GetComponent<Rigidbody>();
}
void FixedUpdate () {
PlayerJump();
}
void PlayerJump(){ //Controls jumping.
if((canJump == true) && (Input.GetKeyDown(KeyCode.Space))){
Vector3 jump = new Vector3(0, jumpSpeed, 0);
rb.AddForce(0f, 0f, 0f);
rb.AddForce(jump, ForceMode.Impulse);
}
}
//Checks if the player is on ground.
void OnCollisionEnter(Collision other){
if(other.gameObject.tag == "Ground"){
canJump = true;
}
}
void OnCollisionExit(Collision other){
canJump = false;
}
//==================================
a) Check for the jump input in Update(). You can safely add a 1 time force in Update(), also, unless there is more in FixedUpdate that was removed for your post. If that’s the case, and you’d rather have it there, then you can set a bool value to true, for the jump input, and once it’s “consumed” in FixedUpdate() set it back to false. This could prevent possibly having 2 fixed updates run in a row - maybe that was your issue, I’m not sure.
b) You might want to check that you left the proper tag when setting ‘canJump’ to false in the exit collision.
c) It might be better still to check if you’re grounded with a small raycast; I find that’s a lot easier, but to each their own.
After putting canJump to false after adding force it hasn’t had the inconsistent jump at all! I really appreciate the help! As for using a raycast, I saw a lot of places suggesting that but I’m just kinda tinkering right now. Anyway thanks again for the help!
Thank you so so much i was struggling as well my code was so close to this but i was using AddRelativeForce and my RigidBody was not set up correctly im kinda a noob at this so thank a ton mate
I know that his is an old thread. But just wanted to say, it did exactly solve my problem (although i am not using a RB, bot moving my character with a CC instead).
The tip with switching off the gravity that is needed to keep the isGrounded stable during take-off was exactly the right one !