# How do I find an angle between 2 rays?

Hey all. So I’ve been working on a raytracer, and I a want to implement specular lighting. Which makes reflective objects appear more shiny.

Now this is cool and all, but I have no idea how I am suppose to find the angle between 2 rays that I will need to make this work.

How do I do this?

Help would be greatly appreciated as always

My current code:

``````function ProcessSpecularLighting(IntersectPos, OriginalColor) -- OriginalColor is the color of the pixel on the screen
local SunRayOrigin = (CFrame.new(IntersectPos, IntersectPos + SunDirection) * CFrame.new(0, 0, 0.1)).Position
local SunRayDirection = (CFrame.new(IntersectPos, IntersectPos - SunDirection) * CFrame.new(0, 0, 0.1)).Position

local SunLightRay = workspace:Raycast(SunRayOrigin, SunRayDirection, Params)

if SunLightRay then
local ReflectedSunDirection = SunRayDirection - (2 * SunRayDirection:Dot(SunLightRay.Normal) * SunLightRay.Normal) -- Relfect the direction.

local Shininess = nil -- a percentage from 0 - 1 that is used for the colour combining below

return Color3.new(1, 1, 1):Lerp(OriginalColor, Shininess) -- Merge the two colours depending on the shininess of the angle
else
return OriginalColor
end
end
``````

1 Like

`math.acos(a.Unit:Dot(b.Unit))` will give you the angle between two vectors a and b.

However, I don’t think your reflection code is correct—your `Dot`ing the sun vector with itself, when that should be with the surface normal.

4 Likes

I believe you do so by finding the dot product.

``local angle = acos(SunlightDirection:Dot(-CameraDirection)) -- in radians``
3 Likes

oh, sorry. Is this correct?

``local ReflectedSunDirection = SunRayDirection - (2 * SunRayDirection:Dot(SunLightRay.Normal) * SunLightRay.Normal) -- Relfect the direction.``
2 Likes

Yes, the dot product of 2 vectors is equal to the product of the length of those vectors times the cos(angle). You can rewrite the formula to get the angle.
In math terms:

Here’s an useful resource:

EDIT: This might be useful if you want to calculate light reflections: Light Reflection Simulation - Roblox Scripting Showcase - YouTube

1 Like

This isn’t quite the right approach for this case. We want to get rid of the negatives out the dot product we return from these unit rays cause then we basically get a value from 0 to 1 representing the shadow angle. To add on you need to raise this mixture float to some exponent, usually called k. I coded this up quickly in bkcore just to show what i mean

1 Like

Agreed, I was just answering the title’s question and fixing an unrelated bug I noticed (OP edited the post after)

You’re def right though, you don’t really need the actual angle that OP described for specular highlights, just the dot product.

1 Like