In my game, you have to press (or more accurately release) space bar to jump. However, at seemingly random instances the player wouldn't jump. So it is working fine most of the times but then out of nowhere, the cube doesn't jump even when input is given. Please help!
public float horizontalSpeed = 0.5f;
Rigidbody rb;
public float JumpHeight = 10f;
private bool onGround;
public float forwardSpeed;
public float rotSpeed;
private float increaseJumpBy = 1f;
private bool increaseJumpHeight;
private bool jumped = false;
public SimpleHealthBar healthBar;
private float Horizontal;
private float Forward;
Vector3 forwardMovement;
Quaternion verRotation;
Vector3 horizontalmovement;
public float maxJump;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
onGround = true;
Forward = Time.deltaTime * forwardSpeed;
forwardMovement = new Vector3(0f, 0f, Forward);
verRotation = Quaternion.Euler(rotSpeed * Time.deltaTime, 0f, 0f);
}
private void FixedUpdate()
{
rb.MovePosition(transform.position + forwardMovement);
Jump();
}
// Update is called once per frame
void Update()
{
healthBar.UpdateBar(JumpHeight, maxJump);
}
void Jump()
{
//Debug.Log("Jumpheight" + JumpHeight);
if(onGround)
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow))
{
if (JumpHeight < maxJump)
{
increaseJumpHeight = true;
}
}
if(JumpHeight>= maxJump)
{
JumpHeight = maxJump;
}
if (increaseJumpHeight)
{
JumpHeight += increaseJumpBy;
}
if (Input.GetKeyUp(KeyCode.Space) || Input.GetKeyUp(KeyCode.UpArrow))
{
rb.velocity = new Vector3(0f, JumpHeight, 0f);
onGround = false;
increaseJumpHeight = false;
jumped = true;
}
if (jumped)
{
JumpHeight = 0;
jumped = false;
}
}
if (!onGround)
{
Horizontal = Input.GetAxis("Horizontal");
horizontalmovement = new Vector3(Horizontal * horizontalSpeed * Time.deltaTime, 0f, 0f);
rb.MovePosition(transform.position + horizontalmovement + forwardMovement);
Quaternion horRotation = Quaternion.Euler(0f, 0f, Horizontal * horizontalSpeed * Time.deltaTime);
rb.MoveRotation(rb.rotation * verRotation /*horRotation*/);
}
}
void OnCollisionEnter(Collision collision)
{
onGround = true;
}
void OnCollisionExit(Collision col)
{
onGround = false;
}
Edit: Removing the bool jumped
and adding JumpHeight = 0
to if(!onGround)
seems to solve the problem
onGround
,jumpHeight
, andjumped
when the jump fails (and the working jump immediately before the failure for comparison). \$\endgroup\$onGround
value (see above). I am not sure if that's the cause of the issue. I can't record the exact value ofonGround
due the fast pace nature of the game (see above). \$\endgroup\$jumped
value always appears as false regardless if the jump fails or not. Is this the source of the issue? @KevLoughrey \$\endgroup\$