- Home /
Create a 2D line reflection (laser trace)
Hello,
I'm trying to implement a line (laser) collides with some scenery objects. After my search, I saw that we can use LineRender with the Reflect function of a Vector3 (Vector3.Reflect). But still no success with my implementation (maybe I have not understood how it works).
It should look like the sample images below:
...As the dotted line blank.... ^
I have the initial code:
var hit : RaycastHit;
private var point01 = Vector3 (0,0,0);
function Start () {
line = this.gameObject.AddComponent (LineRenderer);
}
function Update () {
line.SetPosition(0, point01); Physics.Raycast(transform.position,transform.forward,hit);
if(hit.collider) {
line.SetPosition(1,Vector3(0,0,hit.distance));
line.SetPosition(2, Vector3.Reflect(Vector3(0, 0, hit.distance), Vector3.right));
}
else
{
line.SetPosition(1,Vector3(0,0,5000));
}
}
What would be the best way to get the image results?
Any suggestions will be of great help.
Thank you in advance.
Untested, but try this:
if(hit.collider) {
line.SetPosition( 1, hit.point );
line.SetPosition( 2, hit.point + 100.0f * Vector3.Reflect(transform.forward, hit.normal) );
}
else
{
line.SetPosition( 1, transform.position + transform.forward * 100.0f );
}
Answer by BratianuCosmin · Aug 19, 2020 at 11:48 AM
some Inspiration
public class AimLine : MonoBehaviour
{
RaycastHit2D oldHit;
RaycastHit2D hit2;
LineRenderer Line;
public float MAXdistance;
private void Start()
{
Line = GetComponent<LineRenderer>();
}
private void Update()
{
float totaldistance = 0;
Line.positionCount = 1;
Line.SetPosition(0, Vector3.zero);
oldHit = Physics2D.Raycast(Vector3.zero, (Vector2)transform.up, 200f);
var direction = Vector2.Reflect(transform.up, oldHit.normal);
for (int i = 0; i < 100; i++)
{
if (totaldistance < MAXdistance)
{
if (oldHit.collider)
{
totaldistance += oldHit.distance;
Line.positionCount++;
Line.SetPosition(Line.positionCount - 1, oldHit.point);
oldHit.collider.enabled = false;
hit2 = Physics2D.Raycast(oldHit.point, direction, 200f);
direction = Vector2.Reflect(direction, hit2.normal);
oldHit.collider.enabled = true;
oldHit = hit2;
}
}
else
{
break;
}
}
}
}
Your answer
Follow this Question
Related Questions
Laser Render Reflect Angle incorrect 1 Answer
Dynamically adjusting LineRenderer vertexes to follow raycasts 0 Answers
LineRenderer (Laser Beam) is not following the ray it's going on the wrong direction when reflecting 1 Answer
Only One LineRenderer Renders 0 Answers
LineRenderer End Width Bug 2 Answers