Lightning Effect CFrame Maths

Hey, I’m trying to make a lightning effect, I’ve almost got it but I have a small problem which I’m unsure how to fix.


As you can see, the different parts of the lightning don’t join up.

local parts = {}
local prev = assets.Parts["Lightning Part"]:Clone()
prev.Parent = debris
prev.CFrame = hrp.CFrame * CFrame.new(0,0,-4) * CFrame.Angles(math.random(-15,15)*math.pi/2,math.random(-15,15)*math.pi/2,math.random(-15,15)*math.pi/2)
table.insert(parts, prev)
for i = 1, 20 do
	local part = assets.Parts["Lightning Part"]:Clone()
	part.Parent = debris
	part.CFrame = prev.CFrame * CFrame.new(0,0,prev.Size.Z) * CFrame.Angles(math.rad(math.random(-15,15)),math.rad(math.random(-15,15)),math.rad(math.random(-15,15)))
	prev = part
end

How can I change this to make it so the parts join up?
image

2 Likes

Take a look at this video

1 Like

we can use Pivot Tools to set the lightning part like this


then we can use the pivot to position the parts

local part = assets.Parts["Lightning Part"]:Clone()
part:PivotTo(cFrame)
part.Parent = debris

for i = 1, 20 do
	-- clone the previous part
	part = part:Clone()
	-- move it along its look vector by the size of the part
	part.Position += part.CFrame.LookVector * part.Size.Z
	-- get the parts cframe
	local cFrame = part:GetPivot()
	-- rotate the cframe
	cFrame *= CFrame.Angles(math.rad(math.random(-15,15)), math.rad(math.random(-15,15)), math.rad(math.random(-15,15)))
	-- update the parts cframe
	part:PivotTo(cFrame)
	-- parent the cloned part
	part.Parent = debris
end
1 Like

I figured it out:

for i = 1, 20 do
	local part = prev:Clone()
	part.Parent = debris
	part.CFrame = prev.CFrame * CFrame.new(0,0,-prev.Size.Z / 2) * CFrame.Angles(math.rad(math.random(-15,15)), math.rad(math.random(-15,15)), math.rad(math.random(-15,15))) * CFrame.new(0,0,-prev.Size.Z / 2)
prev = part
end

“CFrame multiplication is not commutative. This means that a * b is not necessarily equal to b * a.”
I had to multiply the CFrames in a specific order in order to get the affect I wanted.
image

1 Like