I was reading an open-sourced script when I found these two really confusing line(Line 9 and 13), so i need someone to explain to me what’s going in the lines. Here is the excerpt:
local Position = StartPosition + (EndPosition - StartPosition).Unit * i * (EndPosition - StartPosition).Magnitude/ NumberOfSegments
local module = {}
module.Lightning = function(StartPosition,EndPosition,NumberOfSegments)
local Points = {}
local Model = Instance.new("Model")
Model.Name = "LightningModel"
Model.Parent = workspace
for i = 0 , NumberOfSegments do
local Offset = Vector3.new(math.random(-17,17),math.random(-17,17),math.random(-17,17)) --Offset that is to be used for later
local Position = StartPosition + (EndPosition - StartPosition).Unit * i * (EndPosition - StartPosition).Magnitude/ NumberOfSegments
if i == 0 or i == NumberOfSegments then
Offset = Vector3.new(0,0,0)
end
Points[#Points +1] = (StartPosition - EndPosition).Unit * i * (EndPosition - StartPosition).Magnitude / NumberOfSegments + Offset
end
end
return module
Still not the clear explanation I was looking for.
What is the purpose for multiplying by i?
What is the purpose of doing (EndPosition - startposition).Magnitude/Number of segments?
what is the purpose of multiplying all that with (EndPosition - startposition).unit?
What is the purpose of adding all that to start position?
For the second line, why loop through the table again adding 1 with points[#points + 1]? then doing the same thing as the first line?
Looks like a bad Lerp function. Better to use the built-in one.
Edit: If you want to know how it works:
First, you see everything is added to StartPosition. It’s an offset from the start.
Then, there’s (EndPosition - StartPosition).Unit. That’s a vector with length one that goes from StartPosition towards EndPosition.
Then * i. The length is now based on whatever iteration of the loop it’s on.
Then * (EndPosition - StartPosition).Magnitude. .Unit * .Magnitude from earlier is just straight up EndPosition - StartPosition. They could’ve just done (EndPosition - StartPosition) * i instead of this mess, hence the “bad Lerp function” I called it earlier.
Then / NumberOfSegments. i / NumberOfSegments is what percent of the loop is done. Overall the function offsets StartPosition so it’s i% of the way to EndPosition. You could just do StartPosition:Lerp(EndPosition, i / NumberOfSegments), though.