- Home /
The question is answered, right answer was accepted
Problem with raycast
Hi I have a problem with a raycasting. I wanted to use it to check if player is on ground but ray isn't detecting anything, becuse it doesn't start at the bottom of model but on center of it.
hit = Physics2D.Raycast(transform.position, -Vector2.down, jumpMargin);
if (hit.collider != null)
{
Debug.LogWarning(hit.collider);
onGround = true;
Debug.LogWarning("onGround");
//if (hit.collider.tag == "Floor" || hit.collider.tag == "Box")
}
else
{
onGround = false;
Debug.LogWarning("inAir");
}
Just $$anonymous$$ake Empty GameObject under your player and cast ray from that gameObject.
Answer by Piyush_Pandey · May 23, 2017 at 11:00 AM
You are raycasting from the center position. The reason it not detects the floor might be because its not long enough. You can find the bottom most point of you sprite, and then raycast from here.
private Vector3 bottomCheckPosition;
private Transform thisTransform;
void Start()
{
thisTransform = transform;
bottomCheckPosition = GetComponent<BoxCollider2D>().size.y/2;
}
void Update()
{
Vector2 checkPos = new Vector2(thisTransform.position.x , thisTransform.position.y-bottomCheckPosition , thisTransform.position.z)
Ray hit = Physics2D.Raycast(checkPos, -Vector2.down, jumpMargin);
if (hit.collider != null)
{
Debug.LogWarning(hit.collider);
onGround = true;
Debug.LogWarning("onGround");
//if (hit.collider.tag == "Floor" || hit.collider.tag == "Box")
}
else
{
onGround = false;
Debug.LogWarning("inAir");
}
}
Also, i would suggest not to use -Vector2.down
because its magnitude is just 1. You can use new Vector2(0 , - downwardDistance)
where you can control the magnitude of how much it should go in that direction.