I am new to unity and was trying to put in raycasting to see if the player is grounded. However, it seems to do nothing as my character can still jump in the air. What am I doing wrong?
using UnityEngine;
public class Player2dController : MonoBehaviour
{
private Rigidbody2D body;
private BoxCollider2D boxCollider;
[SerializeField] private float speed;
[SerializeField] private float jump;
[SerializeField] private LayerMask groundLayer;
private void Awake()
{
//References
body = GetComponent<Rigidbody2D>();
boxCollider = GetComponent<BoxCollider2D>();
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
//flip player in moving direction
if (horizontalInput > 0.01f)
transform.localScale = Vector3.one;
else if (horizontalInput < -0.01f)
transform.localScale = new Vector3(-1, 1, 1);
if (Input.GetKey(KeyCode.Space) && isGrounded())
Jump();
}
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, jump);
}
private bool isGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
return raycastHit.collider != null;
}
}