- Home /
Line Renderer Issues
I needed a 'light' that bounced off gameObjects in the 'Mirror' layer. I decided to use Line renderer, and I cannot see the line being drawn at runtime. I don't know what is the thing that I am doing wrong, but have a look anyways. This is the code that controls the Line Renderer and the raycasting for the line renderer.
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class MirrorReflect : MonoBehaviour
{
public LayerMask layer;
private LineRenderer lineRenderer;
private void Start()
{
lineRenderer = GetComponent<LineRenderer>();
}
private void Update()
{
CalculateReflections(transform.position + new Vector3(1, 0), transform.right);
}
private void CalculateReflections(Vector3 position, Vector3 direction)
{
int reflectionIndex = 1;
RaycastHit2D hit = Physics2D.Raycast(position, direction, 100, layer);
if (hit.collider != null)
{
reflectionIndex++;
lineRenderer.positionCount = reflectionIndex;
lineRenderer.SetPosition(reflectionIndex, hit.point);
Debug.Log(hit.collider.gameObject.name);
if (hit.collider.gameObject.layer == layer)
{
CalculateReflections(hit.point, hit.normal);
}
}
else
{
return;
}
}
}
The raycast is infact hitting the 'mirror' gameobject, as it displays the name in the console, but the line renderer is not updated. Any help is greatly appreciated!
Answer by sean244 · Feb 16, 2019 at 05:20 AM
Try this: before setting the line position, set the z-value of the hit point to -1
hit.point.z = -1;
lineRenderer.SetPosition(reflectionIndex, hit.point);
I found the problem. The reflectionIndex was starting from 1, while an array's start is always 0. so, I had to do lineRenderer.SetPosition(reflectionIndex - 1, hit.point);
to get wanted behavior. Though this works, this condition : if (hit.collider.gameObject.layer == layer)
always fails even if it hits the correct object which is on the correct layer. $$anonymous$$gestions?
Just setting the z-value of the hit point to -1 didn't solve your problem?
hit.point.z = -1;
lineRenderer.SetPosition(reflectionIndex, hit.point);
Your answer
Follow this Question
Related Questions
Linerenderer doesn't match my ray. 1 Answer
Setting Line Render position directly forward from facing of game object 1 Answer
Multiple Cars not working 1 Answer
Bouncing Raycast "Laser" Not Working? 1 Answer
Distribute terrain in zones 3 Answers