Skip to content

Instantly share code, notes, and snippets.

@N-Carter
Created December 20, 2011 14:39
Show Gist options
  • Save N-Carter/1501771 to your computer and use it in GitHub Desktop.
Save N-Carter/1501771 to your computer and use it in GitHub Desktop.
A beam that can be reflected multiple times
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ReflectiveBeam : MonoBehaviour
{
[SerializeField] protected LineRenderer m_LineRenderer;
[SerializeField] protected float m_MaximumDistance = 10.0f;
[SerializeField] protected int m_NumBounces = 10;
protected void Update()
{
var vertices = CalculateBeam();
m_LineRenderer.SetVertexCount(vertices.Count);
for(int i = 0; i < vertices.Count; ++i)
m_LineRenderer.SetPosition(i, vertices[i]);
}
protected List<Vector3> CalculateBeam()
{
var vertices = new List<Vector3>();
Vector3 position = transform.position;
Vector3 direction = transform.forward;
vertices.Add(position);
int numBounces = m_NumBounces;
float remainingDistance = m_MaximumDistance;
RaycastHit hit;
while(--numBounces > 0 && remainingDistance > 0.0f && Physics.Raycast(position, direction, out hit, remainingDistance))
{
remainingDistance -= (hit.point - position).magnitude;
vertices.Add(hit.point - direction * 0.1f);
position = hit.point;
direction = Vector3.Reflect(direction, hit.normal);
vertices.Add(hit.point + direction * 0.1f);
}
if(numBounces > 0)
vertices.Add(position + direction.normalized * remainingDistance);
return vertices;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment