- Home /
Raycast2D Bug
Hello, I have a small error in my game im not sure what causing it. Basically I have a 2D sprite that flips X in SpriteRenederer & when it does a ray should grown in value until it collides with given layers. But for some reason when facing left (Flip X is True) & the ray collides with a gameobject the ray flips facing right. But for the right side the ray is working as it should.
public Transform viewpos;
public float viewdis;
public LayerMask OBJ;
public bool off;
// DETECTION
if (GetComponent<SpriteRenderer>().flipX)
{
RaycastHit2D viewl = Physics2D.Raycast(viewpos.position, -transform.right, viewdis, OBJ);
if (viewl.collider != null)
{
if (!off)
{
viewdis = viewl.collider.transform.parent.gameObject.transform.position.x - 0.54f;
off = true;
}
}
else
{
off = false;
viewdis += 0.05f;
}
Vector3 dirV = transform.TransformDirection(Vector3.left) * viewdis;
Debug.DrawRay(viewpos.position, dirV, Color.red);
}
else
{
RaycastHit2D viewr = Physics2D.Raycast(viewpos.position, transform.right, viewdis, OBJ);
if (viewr.collider != null)
{
if (!off)
{
viewdis = viewr.collider.transform.gameObject.transform.position.x - 0.54f;
off = true;
}
}
else
{
off = false;
viewdis += 0.05f;
}
Vector3 dirVr = transform.TransformDirection(Vector3.right) * viewdis;
Debug.DrawRay(viewpos.position, dirVr, Color.red);
}
Answer by skagontale · Sep 16, 2021 at 11:43 PM
have the code flip the sprite renderer instead of the axis and make a LayerMask on the raycast to haveit only interact with a certain layer. most of this can be researched individuaklly and put togethjer.
it is flipping the sprite renderer & not the axis & their is a layer mask on the ray the problem is the ray flips to the right when it collides with a layer when it should either grow leftwards or stay facing left when colliding with given layers.
Answer by GameDevH2O · Sep 17, 2021 at 04:49 PM
Figured it out had to put Physics2D.Raycast(viewpos.position, -transform.right, -viewdis, OBJ);
& viewdis -= 0.05f;
when facing left. Wish I never posted this question lol.
Your answer
![](https://koobas.hobune.stream/wayback/20220613043120im_/https://answers.unity.com/themes/thub/images/avi.jpg)