Help with bezier curve?

So i tried bezier curve algorithm. it works with 3 and 4 points but it doesnt work with 5 points.

Script
local points = {workspace.p1.CFrame,workspace.p2.CFrame,workspace.p3.CFrame,workspace.p4.CFrame,workspace.p5.CFrame}

local function CP(fra)
	local p = Instance.new("Part",workspace)
	p.Name = "DeleteThis"
	p.Anchored = true
	p.Size = Vector3.new(1,1,1)
	p.CanCollide = false
	p.CFrame = fra
	p.BrickColor = BrickColor.Black()
end
local function bezier(points,percent)
	local tab = {}
	local quadratics = {}
	local endFrame = nil
	local lastIndex = 0
	for i,v in pairs(points) do
		if i < #points then
			local after = points[i + 1]
			if after then
				local linear = v:lerp(after,percent)
				table.insert(tab,linear)
			end
		end
	end
	if #points == 3 then
		for i = 1,#tab do
			if i ~= lastIndex then
				local v = tab[i]
				if endFrame == nil then
					endFrame = tab[i + 1]
					lastIndex = i + 1
				else
					lastIndex = i
				end
				endFrame = v:lerp(endFrame,percent)
			end
		end
	else
		for i = 1,#tab do
			print("lastindex = "..lastIndex.." i = "..i)
				local after = tab[i + 1]
				if after then
					local a = tab[i]:lerp(after,percent)
					table.insert(quadratics,a)
					lastIndex = i + 1
				end
		end
		lastIndex = 0
		print("number of quadratics = "..#quadratics)
		for i = 1,#quadratics do
			if i ~= lastIndex then
				local v = quadratics[i]
				if endFrame == nil then
					print("using index "..i+1)
					endFrame = quadratics[i + 1]
					lastIndex = i + 1
				else
					lastIndex = i
					print("using index "..lastIndex)
				end
				if endFrame == nil then
					print("endframe is nil! using index "..(i - 1))
					endFrame = quadratics[i - 1]
				end
				endFrame = v:lerp(endFrame,percent)
			end
		end
	end
	
	return endFrame
end
local speed = 3
local gravity = workspace.Gravity

local dist = (points[1].p - points[#points].p).Magnitude
local numberOfPoints = math.floor(dist/speed + 0.5)
for i = 1,numberOfPoints do
	wait()
	local percentage = i/numberOfPoints
	local f = bezier(points,percentage)
	CP(f)
end
with 3 points

Roblox Bezier 3

with 4 points

Roblox Bezier 4

with 5 points

Roblox Bezier 5

2 Likes

You would have to define a new curve at the end of the parametric. If you really need it in one continous equation you’d need to use something else like catmul.

k, i found the solution

local function bezier(points,percent)
	if #points >= 3 then
		local tab = points
		repeat
			local newTab = {}
			for i,v in pairs(tab) do
				local after = tab[i + 1]
				if after then
					local result = v:lerp(after,percent)
					table.insert(newTab,result)
				end
			end
			tab = newTab
		until #tab <= 1
		return tab[1]
	end
end

i dont really know how you gonna use catmul on beziers, since when i try to search catmul all i found was catmull-clark algorithm which is used to subdivide.

1 Like