Changing the face of a part

I am currently working on a small project, using inverse kinematics. Though it is not going as expected.

Got the module from this, modified it a bit.

local IKFramwork: table = {}

function IKFramwork.SolveIK(segments: table, startPart: BasePart, endPart: BasePart): nil
	local prevSegment: BasePart? = nil;
	for i = #segments, 1, -1 do
		local goalPosition: Vector3? = nil;
		local currentSegment: BasePart = segments[i];

		-- Set the goalPosition as the endPart if there was not a previous iteration
		if (not prevSegment) then
			goalPosition = endPart.PrimaryPart.Position
		else
			goalPosition = (prevSegment.PrimaryPart.CFrame * CFrame.new(0,0,prevSegment.PrimaryPart.Size.Z)).Position
		end

		local startPositionOfThisSegment: Vector3 = (currentSegment.PrimaryPart.CFrame * CFrame.new(0,0,currentSegment.PrimaryPart.Size.Z)).Position

		-- Set the CFrame from the goalPosition, facing the segment's current start position
		currentSegment.PrimaryPart.CFrame = (CFrame.new(goalPosition, startPositionOfThisSegment) * CFrame.new(0,0,-currentSegment.PrimaryPart.Size.Z)) * CFrame.Angles(0,math.pi,0)

		prevSegment = currentSegment
	end
end

return IKFramwork

Now yeah, this works well. If it wasn’t for one problem, the back segments rotate with the face to the segment infront.


Here the face is at the bottom of this segment. I can’t really change it as it is a cylinder.


Now this is what it looks like when running… Completely wrong, it isn’t supposed to be like this.

How do I fix it?