Hello! I’m making a simple 2D platformer and I wanted to use Unity’s Raycast2D feature to check collisions. I have a scene set up, and everything is working fine so far, only sometimes after jumping, the raycast gets “stuck” in the ground instead of “stopping” the player. Does anybody know why this might be? Am I wrong for even trying to detect collisions in this way?
(below is the code in my update function)
/** RAYCASTING */
//send out a ray detecting whether or not you are on ground
Ray2D ray = new Ray2D(new Vector2(transform.position.x, transform.position.y), new Vector2(0, -1));
Debug.DrawRay(ray.origin, ray.direction * 0.5f, new Color(255f, 0f, 0f));
RaycastHit2D rayHit = Physics2D.Raycast(ray.origin, ray.direction, 0.5f);
if (rayHit)
{
onGround = true;
yVelocity = 0;
}
else
{
onGround = false;
yVelocity += gravity;
}
/** CONTROLS */
//if jump, then jump!
if (Input.GetButtonDown("Jump") && onGround == true) {
yVelocity += jumpVelocity;
onGround = false;
}
//horizontal movement
xVelocity = acceleration * Input.GetAxis("Horizontal");
/** UPDATE POSITION */
//update currentPosition to += xVelocity, yVelocity
currentPosition.x += xVelocity * Time.deltaTime;
currentPosition.y += yVelocity * Time.deltaTime;
//update transform.position to == currentPosition
transform.position = currentPosition;
//then slow down xVelocity
xVelocity *= 0.9f;

