- Home /
[solved]Problem with Raycast2d and LineRenderer
I want to make a line that reflects in everything until it reaches the max length, but i don't understand why my code isnt working.
public float LineLenght;
public int MaxPoints = 4;
LineRenderer line;
Vector3 startline;
Vector3 direction;
void Start()
{
line = GetComponent<LineRenderer>();
}
void Update()
{
if (!line.enabled)
{
return;
}
line.positionCount = 1;
line.SetPosition(0, transform.position);
startline = transform.position;
direction = transform.up;
float Length = LineLenght;
for (int i = 0; i < MaxPoints; i++)
{
RaycastHit2D Hit = Physics2D.Raycast(startline, direction, Length);
if (Hit.collider != null)
{
line.positionCount += 1;
line.SetPosition(line.positionCount - 1, Hit.point);
Length -= Vector3.Distance(startline, Hit.point);
startline = Hit.point;
direction = Vector3.Reflect(direction, Hit.normal);
}
else
{
line.positionCount += 1;
line.SetPosition(line.positionCount - 1, startline + direction * Length);
Length = 0;
break;
}
}
in some specific positions it works exactly how i want
but as in the second image in every other position i can't get the reflection and also all the remaning reflection points are set in the same spot i was using a while(Length > 0) loop but with this bug it creates an infinity number of points and crashs my unity what is causing this bug? how can i solve it??
Answer by Naggil · Nov 19, 2019 at 10:25 PM
I already solved it the raycast is colling with it self to toggle it off just go to
Edit > Settings > Physics2D
and uncheck "Querries Start in Colliders"
Your answer
![](https://koobas.hobune.stream/wayback/20220612215026im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting line renderer size to raycast hit length 0 Answers
How to add lights and particles at multiple hit points of a Raycast2d? 0 Answers
Failing every method for touch point in Android screen 0 Answers
How can i shoot 2D ball/bounce of wall using Raycast? 1 Answer
Inconsistent Reflection/Ricochet of 2D Lines at Specific Angles via Raycasting and 2D Colliders 2 Answers