- Home /
How to prevent a character from being able to jump mid air ?
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;
}
}
Answer by Captain_Pineapple · Nov 26, 2021 at 03:05 PM
Hey there,
if you have issues with raycasts i can only suggest to always 1. put up a Debug.Log to see what object you actually hit 2. add a Debug.Line to see from where to where your ray actually goes.
Following these 2 points will most likely solve your issue as your ray probably just hits your player and will thus always return true
for isGrounded()
.
This might also reveal for example that your groundLayer layermask is not set up correctly.
Let me know if that helped. If not please share the results of these two points with us.
It was my layermask that wasn't working, thanks! For some reason, the player was on the ground layer and when I put it on default it worked just fine.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Add audio. 1 Answer
External Libraries in C# scripts 1 Answer
Why my object not disappear? 1 Answer