Aligning a spawned in humanoid with the floor

I want to create a function that aligns whatever rig I spawn with the floor.

Currently I try and calculate the Y difference of the HumanoidRootPart compared to the floor before it’s moved (as it’s aligned properly at the start) and use that to try and calculate the difference there should be between the part I want to align with and the height the humanoidrootpart should have.

I am clueless with the math and just tried a few things. I’ve tried asking AI but end up with the same issue; the torso clipping halfway through the ground.

The code:

local function AlignModelToPosition(model, alignPosition)
	local position = model:FindFirstChild("HumanoidRootPart")
	local posy = position.Position.Y
	local vector3pos = Vector3.new(alignPosition.Position.X,alignPosition.Position.Y,alignPosition.Position.Z)
	local floorpos = vector3pos - Vector3.new(0,posy,0)
	local cframe = CFrame.new(vector3pos)
	print(cframe)
	print(floorpos)
	model:SetPrimaryPartCFrame(cframe)
end

The prints:
cframe = 740.210449, 9.5, 768.418762, 1, 0, 0, 0, 1, 0, 0, 0, 1
floorpos = 740.21044921875, -26.56058120727539, 768.4187622070312

I don’t really know where to start. Would love some help!

I’m really confused what you meant here; but if I get the gist of it, if you are trying to make the Character planted on the floor, you can simply use a Raycast, then offset the height to the humanoidrootpart.

local function PlantPartToFloor(Part)
	local Origin = Part.Position -- Im adding this here just incase you want to change the origin
	
	local Raycast = workspace:Raycast((Origin + Vector3.new(0, 10, 0)), (Origin - Vector3.new(0, 100, 0)))
	
	if Raycast then
		Part.Position = Raycast.Position + Vector3.new(0, HeightOffset, 0)
	end
end

PlantCharToFloor(Part)

This function can be used as your based; as I am confused with your goal and whether your character is anchored or not.