Controller.isGrounded is jumping on and off. Why?

Here’s the custom controller script:

	CharacterController controller = GetComponent<CharacterController> ();
		if (controller.isGrounded) {
			moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
			moveDirection = transform.TransformDirection (moveDirection);
			moveDirection *= speed;
			if (Input.GetKeyDown ("space") && blockOn == false)
				moveDirection.y = jumpSpeed;
				anim.SetBool ("Jump", true);
				JumpOn = true;
		}
		moveDirection.y -= gravity * Time.deltaTime;
		controller.Move (moveDirection * Time.deltaTime);

So when i walk downhill,it jump on/off and my walk anim glitches. What code do i insert to avoid this problem? Thx in advance.

You’re not enclosing the jumping code between brackets, so this is what it’s happening:

  • if Input.GetKeyDown(“Space”) then it runs the following line (moveDirection…)
  • play the jump animation (line 8), that I suppose moves the body up (so next frame it’s not grounded)
  • set JumpOn as true

You have to enclose the body in brackets if you want the whole block to be run if the player hits space:

if (Input.GetKeyDown ("space") && blockOn == false) {
	moveDirection.y = jumpSpeed;
	anim.SetBool ("Jump", true);
	JumpOn = true;
}