I need help finding a position between two positions

I am trying to make a lightning effect and I understand how I should go about doing it but I am stuck on a certain step. So far I’ve decided that I should get an established beginning and end position, connect them together in a straight line, establish equally spaced points on that line, and apply a random offset then connect the points together. Though i cannot figure out how I can get equally spaced points on the line. I haven’t done this kind of math in a while so I cannot remember what the formula is to get a point on a line. Here is my code so far:

function createLightningPath(start,finish) --start is the starting position, finish is the end position
	local points = {}
	table.insert(points,start)
	local numPts = 5 --number of points i would have on the line
	local len = (finish - start).Magnitude  --not sure how i should use this
	
	for i=1,numPts,1 do
		local offs = Vector3.new(math.random(-1,1),math.random(-1,1),math.random(-1,1))
		local pos    --here I do not know how i can get the next point
		pos = pos + offs
		table.insert(points,pos)
	end
	table.insert(points,finish)
	return points
end
1 Like

To find a point between Vector3s, you could use Vector3:Lerp().

MidPoint = start:Lerp(finish, 0.5) -- this would return a Vextor3 that is halfway between the two points, since 0.5 is half of 1.

You could swap out 0.5 for any value from 0 to 1, depending on where you want the point to be located between the points.

7 Likes

I think the math for that is a weighted average and looks something like:
x = (1-t) * pt1_x + t * pt2_x
y = (1-t) * pt1_y + t * pt2_y
z = (1-t) * pt1_z + t * pt2_z

The t is a value between 0 and 1 (at 0 it’s all the way at the first point and at 1 it is at the second). You would just divide 1 by the numPts to get a step and calc points with t=i*step.

2 Likes

Is this valid?

local start = Vector3.new(16,10,-20)
local finish = Vector3.new(30,12,-5)
local numPts = 5
local i = 2 --just to test

local t = i * (1/numPts)  --0.4
--(1 - t) * start.XYZ + t * finish.XYZ
local x = 21.6
local y = 10.8
local z = -14

And doing start:Lerp(finish, 0.4) should return the same 3 values?

Looks right to me, though I can’t confirm that Lerp would give the exact same values… I assume it would. Pretty sure it’s doing basically that.

Here’s a version with the for loop.

local step = 1/numPts
for i = 0, numPts do
	local t = i * step
	local x = (1-t)*start.X + t*finish.X
	local y = (1-t)*start.Y + t*finish.Y
	local z = (1-t)*start.Z + t*finish.Z
	
	print(x,y,z)
end

(also numPts would technically be the number of equal segments between the two given points. There will be n+1 points)

2 Likes

That answers my question perfectly. Thank you!

1 Like