- Home /
How to stop linerender when it hits an object
I'm making a FPS and am trying to give my gun a laser sight(so a laser pointer basically) and am having trouble with my script as the laser still shines trough walls and does not stop like i want it to.
function Update () { var LaserSight : GameObject; var hit : RaycastHit; Physics.Raycast(transform.position, transform.forward, hit); if (hit.collider) { LaserSight.SetPosition(1, Vector3(0,0,hit.distance)); } else { LaserSight.SetPosition(1, Vector3(0,0, 5000)); } }
I also tried this code
function Update () {
var lineRenderer : LineRenderer = GetComponent(LineRenderer);
lineRenderer.useWorldSpace = false;
lineRenderer.SetVertexCount(2);
var hit : RaycastHit;
Physics.Raycast(transform.position,transform.forward,hit);
if(hit.collider){
lineRenderer.SetPosition(1,Vector3(0,0,hit.distance));
}
else{
lineRenderer.SetPosition(1,Vector3(0,0,5000));
}
}
@script RequireComponent(LineRenderer)
Why do you use if(hit.collider)
ins$$anonymous$$d of if (Physiccs.Raycast(...))
?
Also the RaycastHit argument should have the out keyword.
Answer by doublemax · Oct 05, 2016 at 05:23 AM
The endposition of the line renderer looks strange in both cases. Also: don't forget to set the start positon of the line renderer.
Try something like this:
lineRenderer.SetPosition(0, transform.position );
if(hit.collider){
lineRenderer.SetPosition(1, hit.point);
}
else {
lineRenderer.SetPosition(1, transform.position + transform.forward * 100.0f );
}
It is set to useWorldspace = false, so I guess start position is 0,0,0 always. I guess hit.distance needs to be scaled to world space to make it work (the gun probably has a scale). Or he could switch to worldSpaceCoords and use the above code. :)
Answer by GuruJeya14 · Feb 02, 2019 at 08:20 AM
(I know this conversation occurred long time ago. For people who are in search of the same question....)
Try using Physics.Linecast for our line renderer, instead of Physics.Raycast.
Also check this out, it is explained well by @tsnyder321
Your answer
![](https://koobas.hobune.stream/wayback/20220612093936im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
LineRenderer not working 0 Answers
LineRenderer Not working when parented 1 Answer
Lightaber effect? 0 Answers
LineRendering Forward 1 Answer
LineRenderer or Particles 1 Answer