# Lets refract a laser in Unity

In my previous post titled Reflecting laser light in Unity, I talked about reflecting a laser beam through simulated mirrors. I then thought to myself, if I am reflecting light, why not refract it as well and make the game a bit trickier?

The break down of this problem is pretty easy:

1. First, we need to shoot the light and check whether it hits an object tagged as lens or not.
2. If the laser hits a lens, we refract the light.

I would recommend before proceeding through article that you read the “Reflecting laser light in Unity” as it goes in details through some of the functions that I will go mention in this article.

To detect the type of the object we hit, I had to update the function CheckHit() by adding an additional “else if” statement to check for a collision with a lens. The updated function looks like this:

The first thing we need to do, just like the reflection, is to store the point of impact on the lens on the list of indices of the LineRenderer and from there we need to calculate the refracted direction of the new laser beam. After spending a lot of time learning about physics, I found a law called Snell’s Law that is used to describe the relationship between the angles of incidence and refraction, when referring to light or other waves passing through a boundary between two different isotropic media, such as water, glass, or air. If we assume that when the beam is not touching the lens it is traveling through the air, and when it hits the lens it travels through glass, then we have to use that law to calculate the refracted direction of the light when it passes from the air to the glass. This is Snell’s law:

where n1 is the refractive index of medium 1, n2 is the refractive index of medium 2, l is the direction of the light that is hitting the surface and n is the normal of the surface, theta1 is the angle between the light and the surface and theta2 is the angle between the refracted vector and the surface.

in figure1, you can see that n1 and n2 is set from two constants that were declared and initialized in the class with refractive indices depending on the media type, the vector norm is set to the normal of the hit.point and the incident corresponds to the direction of the laser when it hits the lens. Then we come to the most important function which is Refract() where the refracted vector is calculated through Snell’s law. the function looks like this: