I intended to use OnCollisionStay2D to check when object touched the ground to set “bool grounded” to “true” and set “bool grounded” to “false” when it’s not. However “grounded” is always set to “true” in game and I can call the Jump() method as many times as I want.
public class PlayerMovement : MonoBehaviour
{
[SerializeField] float moveSpeed = 10f;
[SerializeField] Vector2 jumpForce;
bool grounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
{
HorizontalMovement();
Jump();
}
}
private void HorizontalMovement()
{
var HorizontalInput = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var newXPos = (transform.position.x + HorizontalInput);
transform.position = new Vector2(newXPos, transform.position.y);
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && grounded == true)
{
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
grounded = true;
} else { grounded = false; }
}
}