My jumping only works sometimes

Hello to all,

I am haing some difficulty, as while working on jumping i have the issue of my character not jumping each time i press on the space bar (Once it hits the ground of course). Somtimes i have to press it 3-4 times to jump and sometimes it jumps everytime i press space. Is there any reason from my code that that is happening… or is it just my spacebar being stubborn xD

public class Controller : MonoBehaviour
{
Rigidbody rb;

float xInput, zInput;
public float speed;

public float jumpforce;

public LayerMask GroundLayer;

public SphereCollider Col;

float fallmult = 2.5f;
float lowjump = 2f;

private void Awake()
{
rb = GetComponent();
Col = GetComponent();
}

void Update()
{
xInput = Input.GetAxis(“Horizontal”) * speed ;
zInput = Input.GetAxis(“Vertical”) * speed;
}

private void FixedUpdate()
{
rb.velocity = new Vector3(xInput, rb.velocity.y, zInput);

if (IsGrounded() && Input.GetButtonDown(“Jump”))
{
rb.AddForce(Vector3.upjumpforceTime.deltaTime, ForceMode.Impulse);
}

if(rb.velocity.y < 0)
{
rb.velocity += Vector3.up * Physics.gravity.y * (fallmult-1) * Time.deltaTime;
}
else if(rb.velocity.y>0 && !Input.GetButton(“Jump”))
{
rb.velocity += Vector3.up * Physics.gravity.y * (lowjump - 1) * Time.deltaTime;
}
}

private bool IsGrounded()
{
return Physics.CheckCapsule(Col.bounds.center, new Vector3(Col.bounds.center.x, Col.bounds.min.y, Col.bounds.center.z), Col.radius * 0.9f, GroundLayer);
}

}

Thanks for any and all input you may provide :slight_smile:

Best Regards,

Please use code tags: Using code tags properly

Don’t check for edge-trigger Up or Down type events in FixedUpdate().

Instead, check for Up/Down events in Update() and set a boolean, then “consume” that boolean in FixedUpdate() and clear it back out.

Here’s specifically why checking in FixedUpdate() fails:

Thank you very much for your quick reply.

I will look into your solution :slight_smile:

Sorry also for not using code tags, didnt know how to do that before posting. Next time i will remember to use them :slight_smile:

Best Regards,

It Worked :smile:

Thanks so much.

Though there are some errors popping up.

----The referenced script (Unknown) on this Behaviour is missing!
----The referenced script on this Behaviour (Game Object ‘Player’) is missing!

But ill try and figure that out myself.

Thanks again :slight_smile:

I am confident that you can with an attitude like that… GO!

Here is my standard blurb about those:

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above.