- Home /
Character doesn't jump repeatedly
Hello everyone. I have a code that works well for me. But I'm having trouble making my character just jump once while the button is pressed. Current mode the character jump repeatedly while the button is pressed and I don't want that. Can anyone help?
private void UpdateVelocity() {
Vector3 velocity = rigidbody.velocity;
if (grounded) velocity = Util.ProjectOntoPlane(velocity, transform.up);
if (grounded) {
// Apply a force that attempts to reach our target velocity
Vector3 velocityChange = (desiredVelocity - velocity);
if (velocityChange.magnitude > maxVelocityChange) {
velocityChange = velocityChange.normalized * maxVelocityChange;
}
rigidbody.AddForce(velocityChange, ForceMode.Impulse);
if (Input.GetButton("Jump")) {
rigidbody.AddForce(Vector3.up*jumpHeight, ForceMode.Impulse);
transform.localEulerAngles = new Vector3(0 , transform.localEulerAngles.y, transform.localEulerAngles.z);
}
}
rigidbody.AddForce(transform.up * -gravity * rigidbody.mass);
grounded = false;
}
your code is a bit messy. For example you check twice if char is grounded( lines 5 and 13) . Also why do you have a canJump bool , isnt the fact that your player is grounded enough for him to be able to jump. the same goes for jumppressed and Input("jumpbutton")
You still check if(grounded) twice, at lines 3 and 5. Also you always set grounded to false at the end of UpdateVelocity when I'm guessing you only want grounded to be set to false if the player jumps.
Answer by thadstedman · Nov 24, 2020 at 07:46 PM
Try changing this:
if (Input.GetButton("Jump")) {
}
to this:
if (Input.GetButtonDown("Jump")) {
}
I could be wrong, but I think now you are checking if the button is currently being held down but if you change it to GetButtonDown then it only triggers when you first press it.