I create a weapon that fires a ray that reflects through walls, and I use LineRenderer to visualize it. Here’s the code, which is pretty straightforward:
public float range = 15f;
public int damage = 3;
public LineRenderer trail;
public ParticleSystem hitEffect;
protected override void Shoot() {
float rangeLeft = range;
Vector3 rayPosition = transform.position;
Vector3 rayDirection = transform.forward;
LineRenderer rayRenderer = (LineRenderer) Instantiate ( trail, Vector3.zero, Quaternion.identity );
rayRenderer.SetVertexCount(1);
rayRenderer.SetPosition(0, transform.position);
int vertexCount = 1;
while (rangeLeft > 0f) {
/*
This loop should actually never finish on this condition, and always finish on the break later.
However, I added this just as a precaution against a neverending loop.
*/
RaycastHit hit;
Vector3 rayFinish = rayPosition + rayDirection * rangeLeft;
Debug.DrawLine( rayPosition, rayFinish, Color.green );
if (Physics.Linecast ( rayPosition, rayFinish, out hit ) ) {
Debug.DrawLine( rayPosition, hit.point);
Debug.Log("Ray hit: " + hit.point);
// Instantiating hit effect
Quaternion hitRotation = new Quaternion();
hitRotation.SetLookRotation(hit.normal);
Instantiate(hitEffect, hit.point, hitRotation);
// Reflecting
rayPosition = hit.point;
rayDirection = Vector3.Reflect(rayDirection, hit.normal);
rangeLeft -= hit.distance;
// Adding hit point to the rayRenderer
rayRenderer.SetVertexCount( ++vertexCount );
rayRenderer.SetPosition(vertexCount - 1, rayPosition);
// If we hit something, inflicting damage
Health targetHealth = hit.collider.GetComponent<Health>();
if (targetHealth) {
targetHealth.InflictDamage(damage);
}
} else {
// Adding final point to the line renderer
rayRenderer.SetVertexCount( ++vertexCount );
rayRenderer.SetPosition( vertexCount - 1, rayFinish );
break;
}
}
Debug.Break();
}
And here’s how it looks at breakpoint:
As you can see, the debug drawLines indicate that my code appears to work correctly — lines are reflected by walls, it’s very straightforward. However, the LineRenderer lines are crooked, with strange in-between angles. Why is it happening? I used LineRenderer in a similar fashion before for straight lines, and didn’t experience any of such problems. Is there a bug in my code that I can’t see, or is there a bug in LineRenderer functionality?
