How to make snake part/segment spawn from the last snake part/segment

  1. What do you want to achieve? Keep it simple and clear!

i was making a slither/snake type game system. following a devforum post using an IK module, but the segements spawn on the front of the segment, so how do i make it spawn from the last segment?

What happened:

what i want it to look like:

snaketest

IK Module:

local IKFramwork = {}

function IKFramwork.SolveIK(segments, startPart, endPart)
	local prevSegment = nil;
	for i = #segments, 1, -1 do
		local goalPosition;
		local currentSegment = segments[i];
		
		-- Set the goalPosition as the endPart if there was not a previous iteration
		if (not prevSegment) then
			goalPosition = endPart.Position
		else
			goalPosition = (prevSegment.CFrame * CFrame.new(0,0,prevSegment.Size.Z/2.2)).p
		end
		
		local startPositionOfThisSegment = (currentSegment.CFrame * CFrame.new(0,0,currentSegment.Size.Z/2.2)).p
		
		-- Set the CFrame from the goalPosition, facing the segment's current start position
		currentSegment.CFrame = (CFrame.new(goalPosition, startPositionOfThisSegment) * CFrame.new(0,0,-currentSegment.Size.Z/2.2)) * CFrame.Angles(0,math.pi,0)
		
		prevSegment = currentSegment
	end
end

return IKFramwork

Main Script:

-- segments is a table with spheres of the snake(segments)
-- primary is character HumanoidRootPart

RunService.Heartbeat:Connect(function()
IkModule(Segments, Primary, Primary)
end)
1 Like

I found the solution, turns out i have to change the order of the table

1 Like