Best way to keep HRP lookvector while trying to align player to the ground

Hi, I’m not very good at CFrames :sweat_smile:. I’m trying to align a character to a normal vector while keeping the HumanoidRootPart lookvector. I’m wondering if there is a more efficient solution to keeping it aligned, I ran into one or two but they either required an if statement or two and were off in the math so I won’t put it here.

-- aligning to the ground
RunService.Heartbeat:Connect(function()
	local raycastResult = workspace:Raycast(character.HumanoidRootPart.Position, Vector3.new(0, -5, 0), rayBlacklist)
	if raycastResult then
		character.HumanoidRootPart.CFrame = CFrame.new(character.HumanoidRootPart.Position, character.HumanoidRootPart.Position + raycastResult.Normal) * CFrame.Angles(math.rad(-90), 0, 0)
	end
end)

thanks in advance.

we can use the lookAt constructor

runService.Heartbeat:Connect(function(deltaTime)
	local rootPart = character.HumanoidRootPart
	local position = rootPart.Position
	local direction = -rootPart.CFrame.UpVector * 5
	local raycastResult = workspace:Raycast(position, direction, raycastParams)
	if raycastResult == nil then return end
	rootPart.CFrame = CFrame.lookAt(position, position + rootPart.CFrame.LookVector, raycastResult.Normal)
end)
2 Likes

This advanced CFrame techniques is good for maintaining the look vector as it finds the shortest CFrame rotation from the current UpVector to the new UpVector.

Rather than CFrame.lookAt or CFrame.new which generates a completely new right vector based on Vector3.new(0,1,0) which it crossproducts with based on the new look vector.

1 Like