- Home /
How do I move my raycast from inside my player to outside of it?
I'm making a 2D platformer and my script uses raycasts to stop infinite jumping and for some reason the raycast stays inside the character instead of being outside of it which stops it from checking if I can jump.
This is my code
private void Jump() { RayPositionCenter = transform.position + new Vector3(0, RayLength .5f, 0); RayPositionLeft = transform.position + new Vector3(-RayPositionOffset, RayLength .5f, 0); RayPositionRight = transform.position + new Vector3(RayPositionOffset, RayLength * .5f, 0);
GroundHitsCenter = Physics2D.RaycastAll(RayPositionCenter, -Vector2.up, RayLength);
GroundHitsLeft = Physics2D.RaycastAll(RayPositionLeft, -Vector2.up, RayLength);
GroundHitsRight = Physics2D.RaycastAll(RayPositionRight, -Vector2.up, RayLength);
AllRaycastHits[0] = GroundHitsCenter;
AllRaycastHits[1] = GroundHitsLeft;
AllRaycastHits[2] = GroundHitsRight;
CanJump = GroundCheck(AllRaycastHits);
Debug.DrawRay(RayPositionCenter, -Vector2.up * RayLength, Color.red);
Debug.DrawRay(RayPositionLeft, -Vector2.up * RayLength, Color.red);
Debug.DrawRay(RayPositionRight, -Vector2.up * RayLength, Color.red);
}
private bool GroundCheck(RaycastHit2D[][] GroundHits)
{
foreach (RaycastHit2D[] HitList in GroundHits)
{
foreach(RaycastHit2D hit in HitList)
{
if (hit.collider != null)
{
if(hit.collider.tag != "PlayerCollider")
{
return true;
}
}
}
}
return false;
}
Answer by SamElTerrible · Oct 14, 2021 at 10:06 AM
My guess is that you're casting the ray from the center of your character. If your character has a collider on it, then the ray will hit that collider and stop.
If that's the case, there are a couple of things you can do:
1 - You can tell the raycast to ignore the collision layer of your character.
2 - Move the raycast origin from the center of the character (i.e. transform.position) to slightly outside of its collider (transform.position + (collider size / 2) + 0.01).
IMO, the first solution is a bit cleaner as collisions can only be trusted to a certain extent
Use RaycastAll, filter out the character's colliders yourself.
Follow this Question
Related Questions
2DRaycast is shooting slightly in wrong directions 0 Answers
Raycasting not working? 1 Answer
Raycast Physics2D not working as expected 1 Answer
Raycast2D alternatives 0 Answers