I’m following a beginner Unity course, and the instructor used two nested if statements within a method for jumping logic, as so:
//takes care of jumping logic
private void JumpHandler()
{
//store jump input (Jump axis = up/down axis)
float jAxis = Input.GetAxis("Jump");
//if the key has been pressed
if(jAxis > 0)
{
if(!pressedJump)
{
pressedJump = true;
//jumping vector
Vector3 jumpVector = new Vector3(0, jAxis * jumpForce, 0);
//apply force to rigid body
rb.AddForce(jumpVector, ForceMode.VelocityChange);
}
}
else
{
pressedJump = false;
}
}
As I wrote along, I went with:
if(jAxis > 0 && !pressedJump)
as opposed to the instructor’s two nested if statements.
For some reason, the two approaches produce different results. The nested if statements cause it to function as wanted, wherein the player hits the spacebar and a vertical force is applied in a uniform way, regardless of how long the spacebar was pressed, the player gameobject jumps to the same height. However, my && statement always reads true as long as the spacebar is held down, causing the player gameobject to fly to the stars. What am I missing here? What’s going on?