Understanding the math behind Rays: how is the direction calculated?

When firing a ray, one of the mandatory arguments is the direction of said ray. Most people calculate the direction of a ray for guns using the following line of code:

(mouse.Hit.Position - gunPosition).Unit * range

Where;
mouse.Hit.Positon is the Vector3 value of the CFrame of where the Mouse is hitting (intersection between the Mouse’s ray and a part)
gunPosition is the position of the part on the gun from where the ray will be fired
range is a positive finite number

Now, the goal of this line is to create the ‘directional vector’ of the ray. So, we can separate the line of code into two parts:

(mouse.Hit.Position - gunPosition).Unit
I’m not really sure what the math behind this is. I know the .Unit is creating a unit vector with a specific direction, but how exactly is that direction calculated? How exactly is (mouse.Hit.Position - gunPosition) calculating the direction of the unit vector?

* range
This is fairly simple, its a basic vector scalar multiplication which gives the unit vector a norm.

Thanks a lot!

Hey! Please take a look at this and let me know if you understand.

PS: Excuse my horrible pen-tab handwriting >.<

I understand the graphical concept of vector subtraction, but I’m not sure how this would apply to determining the direction of a ray for a gun for example. How does this transfer over to Roblox??

B would be the point where your gun is at.
A would be the Mouse hit.

Now when you subtract them, you get

Vector C from Vector B to Vector A.

Or in terms of objects, Vector Ray from Vector GunPosition to Vector MousePointer.

And if you project from gun towards the mouse, you get a gunshot towards the intended direction

1 Like

You are correct! Even though the resulting C vector is pointing towards the origin of the A vector (the mouse hit position), since we’re searching for the direction of the resulting vector, and not a specific region in space, you’d be right!

Thanks a lot

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.