Rotate Model towards a Part

Hey there,

I was programming a Tower Defense game and I tried rotating a Tower towards a Cube but it looks weird.

Here’s how everything is set up: There is a sever-side script inside a Tower model in workspace.Towers. The cubes are models in workspace.Cubes and they all contain a BasePart called “Main”. I want a specific model of my tower to rotate towards the cube. The model is called “Rotate” and is located inside Tower > Body > Rotate. The model only has to rotate on its Y axis, ranging from -180 to 180. X and Z remain static.

Here is how I want it to look like:

This is the script that I have right now:

local tower = script.Parent
local rotateModel: Model = tower.Body:FindFirstChild("Rotate")
local range = 50

local function findClosestCube()
	local closestCube = nil
	local shortestDistance = range

	for _, cube in pairs(workspace.Cubes:GetChildren()) do
		local mainPart = cube:FindFirstChild("Main")
		if mainPart then
			local distance = (mainPart.Position - tower:GetPivot().Position).Magnitude
			if distance < shortestDistance then
				closestCube = mainPart
				shortestDistance = distance
			end
		end
	end

	return closestCube
end

local function rotateToCube()
	local closestCube = findClosestCube()
	if closestCube then
		local direction = (closestCube.Position - rotateModel:GetPivot().Position).Unit
		local X, Y, Z = rotateModel:GetPivot():ToOrientation()
		local angle = math.atan2(direction.Z, direction.X)

		-- Update only the Y axis
		print(angle)
		local newOrientation = Vector3.new(X, math.deg(angle), Z)

		rotateModel:PivotTo(newOrientation)
	end
end

while true do
	rotateToCube()
	wait()
end

It gives an error if I execute the script but it doesn’t matter because it has to be rewritten anyway (only the part that rotates the tower).

Can anybody help me with my issue? Thanks a lot!

1 Like

Check the CFrame documentation section about "Facing a specific surface to a point"Or try CFrame lookAt.

Basicly what Scottifly said. I’d use GetBoundingBox to get the models center position, then use the result and closestCube.Position inside of CFrame.lookAt and use that in rotateModel:PivotTo().