Rotation Model toward Object

I am creating a tower defense and I have multiple towers that I am trying to figure out how to rotate toward the nearest mob walking by.

This is my current script; The tower rotation will take place within 'While true do':

Summary
local TweenService = game:GetService("TweenService")
local tower = script.Parent.Position
local mobs = workspace.MobRealm

local function FindNearestTarget()
	local maxRange = 35
	local nearestTarget = nil

	for i, target in ipairs(mobs:GetChildren()) do
		local distance = (target.HumanoidRootPart.Position - tower.Position).Magnitude

		if distance < maxRange then
			nearestTarget = target
			maxRange = distance
		end
	end

	return nearestTarget
end

while true do 
	local target = FindNearestTarget()
	if target then
		local x = target.HumanoidRootPart.CFrame.X
		local y = target.HumanoidRootPart.CFrame.Y
		local z = target.HumanoidRootPart.CFrame.Z
		print(x, y, z)
		x = math.deg(x)
		y = math.round(math.deg(y) / 90) * 90 
		z = math.deg(z)
		print(x, y, z)
		local half = math.pi / 2

		y = math.round(y / half ) * half

		local goal = tower.Parent.PrimaryPart.CFrame * CFrame.Angles(x,y,z)
		print(goal)
		tower.Parent.PrimaryPart:PivotTo(goal)
		print("Complete")
		
	end
	task.wait(.1)
end

As you can see all prints are working.

The tower does not rotate at all, and there are no errors in Output, I just cannot figure out how to get it working.

Not going to attempt to figure out what that math is trying to do:

while true do task.wait(0.1)
	local target = FindNearestTarget()
	if target then
		local target_Pos = target.HumanoidRootPart.Position
		local tower_Pos = tower.Parent.PrimaryPart.Position
		local goal_CFrame = CFrame.new(tower_Pos, target_Pos)
		tower.Parent.PrimaryPart:PivotTo(goal_CFrame)
	end
end
2 Likes

I tried running this and I get no rotation still, I added a print at the end to check if the primarypart was rotating, and it is.

I switched to the model; tower.Parent:PivotTo(goal_CFrame), and now the tower does rotate, but on the side.

Could anyone refer me to an article about adjusting CFrame rotation?