I see some scripters using .Unit in raycasts, for example:
local origin = (Part1.Position - Part2.Position).Unit * 300
Can someone quickly explain what does it do?
I see some scripters using .Unit in raycasts, for example:
local origin = (Part1.Position - Part2.Position).Unit * 300
Can someone quickly explain what does it do?
Yes,
First thing, it gets the direction between two vectors. goal - origin
will be the direction from origin
to goal
.
.Unit “limits” or “extends” the vector to 1 stud. I wrote a topic on that can help visualize unit vectors/length of vectors here
* 300 multiplies the unit vector, so its new length is 300.
So all-in-all this whole thing gives you a directional vector that when the origin is at part2, the vector would be aimed at part1. This directional vector is “extended” or “shortened” to 300 studs (determining whether it’s “extended” or “limited” would differ depending on how far away the parts are from one another, but that isn’t relevant, it should give about the same thing regardless of magnitude, taking into account floating point imprecision)
Okay, so if the origin is Vector3.new(50,50,50) for example, it will be like the range of the raycast?
Sort of, if your direction is 50, 50, 50, the raycast call would cast a ray from whatever origin
is, in the positive X, Y, and Z direction, at an approximately 86.6 stud length. You can see the length by using the vector’s .Magnitude property.
But suppose this part is at the position of ‘origin’.
Your ray with a direction of Vector3(50, 50, 50) visualized would look something like this:
However if you use .Unit on it, the ray will now be “limited” to 1 stud from the origin
If you want to extend it to a target length, you would multiply the unit vector by a number. Say we want it to be 25 studs, then our ray in the direction of positive X, Y, and Z direction at 25 studs would look like this (“calculated” by Vector3.new(50, 50, 50).Unit * 25
)
If you’re seeing something like that example then the original authors of the code are probably getting their terms mixed up. The origin of a raycast is it’s start point, and the calculation you posted looks more like one for determining the translation of a raycast (which is what I call “direction” as described by cody in their reply, I think it’s more precise but translation/directions is not as big a deal as translation/origin or direction/origin). It’s not impossible that some game mechanic needs to make such a calculation for the actual origin of a ray, but IMO it’s not super likely. If you post the actual code I can take another look and see what it’s actually doing and if they’re getting terms mixed up or it’s just a bit of an uncommon case.
Another thing to note is that origin is also the term for the zero- coordinate in any coordinate system, i.e. (0, 0, 0) in 3D.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.