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.