How to solve infinite jumping?

Hello everyone, today i started my Unity journey and I decided to create a controller for my character, although he jumps everytime I click the spacekey in the ground or not, so I decided to follow some tutorials but nothing worked. What might be wrong? Heres the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scr: MonoBehaviour
{
public float speed;
private Rigidbody rb;
public float jumpforce = 1;
private bool isGrounded;

//Vai obter o rigid body do character
void Start()
{

rb = GetComponent();

}
//Movimentaçao do character
void Update()
{
float moveHorizontal = Input.GetAxis(“Horizontal”);
float moveVertical = Input.GetAxis(“Vertical”);
float moveUp = Input.GetAxis(“Jump”);

Vector3 movement = new Vector3(moveHorizontal, moveUp, moveVertical);
rb.AddForce(movement * speed);
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpforce, ForceMode.Impulse);
}
}

}

Where do you set isGrounded to false?

And use Code tags, there is a pinned post on how to use them.

You must change isGrounded with OnTriggerEnter() and add a trigger collider to the object that you attached this script to

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scr: MonoBehaviour
{
public float speed;
private Rigidbody rb;
public float jumpforce = 1;
private bool isGrounded;

//Vai obter o rigid body do character
void Start()
{

rb = GetComponent<Rigidbody>();

}
//Movimentaçao do character
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
float moveUp = Input.GetAxis("Jump");


Vector3 movement = new Vector3(moveHorizontal, moveUp, moveVertical);
rb.AddForce(movement * speed);
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpforce, ForceMode.Impulse);
}
}
//If your game is 2D : void OnTriggerEnter2D(Collider2D col)
void OnTriggerEnter(Collider col)
{
isGrounded = true;
}

//If your game is 2D : void OnTriggerExit2D(Collider2D col)
void OnTriggerExit(Collider col)
{
isGrounded = false;
}

Don’t forget to add a collider to your charachter(positioned in its feet) and set it to Is Trigger"

1 Like

This worked for me.Thank you so much for your contribution mate!