I have a player script that I'm trying to implement jumping in. The problem is that Input.GetButtonDown("Jump") doesn't consistently fire in Update. I know this is a problem when it's in FixedUpdate. Here is my code.
Note: I put [SerializeField] on pressingJump and holdingJump so I could see what's happening. pressingJump is inconsistent (as expected) but holdingJump works perfectly.
using UnityEngine;
public class Player : MonoBehaviour
{
public float fallMultiplier = 15f;
public float lowJumpMultiplier = 10f;
public float walkSpeed = 20f;
public float jumpSpeed = 15f;
public bool canMove = true;
public bool canJump = true;
Rigidbody rb;
float horizontalInput;
bool doJump;
bool pressingJump;
bool holdingJump;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
CaputureInput();
}
void CaputureInput()
{
if (canMove) {
horizontalInput = Input.GetAxisRaw("Horizontal");
}
pressingJump = Input.GetButtonDown ("Jump");
doJump = pressingJump && canJump;
holdingJump = Input.GetButton ("Jump") && canJump;
}
void FixedUpdate()
{
Move();
Jump();
}
void Move()
{
rb.velocity = new Vector2(horizontalInput * walkSpeed, rb.velocity.y);
}
void Jump()
{
if (doJump) {
rb.velocity += Vector3.up * jumpSpeed;
doJump = false;
}
if (rb.velocity.y < 0) {
rb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
} else if (rb.velocity.y > 0 && !holdingJump) {
rb.velocity += Vector3.up * Physics.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
}