Reputation: 818
I've implemented my player movement in such a way that you can't jump again until you've let go of the jump button and pressed it again. For some reason my character randomly jumps sometimes while strictly holding the button down. It is completely random, only happening sometimes and when it does, it just randomly stops eventually, all without releasing the jump button or pressing anything else.
I've narrowed it down to my PlayerMovement script which handles input and sends it to a character controller, the entire script is as follows:
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public Animator animator;
private float horizontalMove = 0f;
private bool jump = false;
private bool dash = false;
private void Update() {
horizontalMove = Input.GetAxisRaw("Horizontal");
if (Input.GetButton("Jump")) {
jump = true;
}
if (Input.GetButtonDown("Dash")) {
dash = true;
}
}
private void FixedUpdate() {
controller.Move(horizontalMove, jump, dash);
jump = false;
dash = false;
}
}
Using various debugging traces, it seems like the issue is in the FixedUpdate() function. The input.getbutton
in Update() is returning the correct 'true' value for the jump button even while the character is jumping erratically. Meanwhile printing the value of jump first thing inside fixedUpdate occasionally gives a random false.
My next guess was that maybe fixedUpdate was sometimes being called multiple times before update() was called, causing it to have those values be false, but I created some more trace to detect when fixedUpdate was double called and it only happened a couple times on startup (runs at 2k+fps during normal play) and not at all while the jumping issue was happening.
Any Ideas?
Upvotes: 0
Views: 379
Reputation: 2974
Character jumping randomly while holding jump button?
The problem lies with how you get your Input. Because you are using Input.GetButton which return true as long as the Button is pressed.
You should only use this when implementing events that trigger an action like for example crouching.
Example:
if (Input.GetButton("Jump")) {
jump = true;
}
// Instead use GetButtonDown:
if (Input.GetButtonDown("Jump")) {
jump = true;
}
Input.GetButtonDown
is only activated once and therefore doesn't produce the jumping while you hold down the button.
Upvotes: 3