# unit – Raycasting – how to correctly do reflection and refraction

I am developing an application for Microsoft Hololens, which should visualize the reflection and refraction of a beam of light. I use a virtual GameObject as a torch (which the user can move) and I do a raycast on each frame. If this beam hits an object, it must be reflected or refracted (depending on the label of the object). However, my code does not work as expected: the beam reflex behavior stops after hitting 2 objects and the refraction does not work at all. Can someone tell me what's wrong with my code and how to fix it?

Here is my current code that does the raycasting:

``````Null update ()
{

RaycastHit hit, hitnext, hitexit;

Vector3 pos = this.transform.position;
Vector3 dir = Vector3.right;
Vector3 dest;

points.Clear ();

pointCount ++;

do
{
Physics.Raycast (pos, transform.TransformDirection (dir), out hit, Mathf.Infinity);

if (hit.collider! = null)
{
if (hit.transform.CompareTag ("Plane")) // if you hit an airplane, do REFRACTION
{
pos = hit.point + 0.01f * dir;

dir = Vector3.LerpUnclamped (dir, -hit.normal, -0.4f);
Debug.Log ("Hit position" + hit.point);
pointCount ++;

// You have entered a collider object, so you must find the exit point ..!
Physics.Raycast (pos, transform.TransformDirection (dir), out hitnext, Mathf.Infinity);
if (hitnext.collider == null) dest = pos + 10000f * dir;
else dest = hitnext.point - 0.001f * dir;

Physics.Raycast (dest, transform.TransformDirection (-dir), out hitexit, 10);

// Having found the starting point ...
pos = hitexit.point + 0.01f * dir;
dir = Vector3.LerpUnclamped (dir, hitexit.normal, 0.4f);
pointCount ++;

}
else // if it is not a plane, do REFLECTION
{
pos = hit.point;

pointCount ++;

dir = Vector3.Reflect (dir, hit.normal);

}
}
} while (puntoCuto <maxPoints && hit.collider! = null);

this.DrawLine (points, Color.red);

}
``````

Then I use the line renderer to draw the collected points.

And here is a screenshot of my scene view: 