Camera:ZoomToExtents

I agree that we should add this as a built in method. But for now if anyone needs this functionality in Lua here is a script which replicates the Zoom Extents behavior in Studio (pressing the F key with a model/part selected).

local function getCameraOffset(fov, extentsSize)
	local halfSize = extentsSize.Magnitude / 2
	local fovDivisor = math.tan(math.rad(fov / 2))
	return halfSize / fovDivisor
end

local function zoomToExtents(camera, instance)
	local isModel = instance:IsA("Model")

	local instanceCFrame = isModel and instance:GetModelCFrame() or instance.CFrame
	local extentsSize = isModel and instance:GetExtentsSize() or instance.Size

	local cameraOffset = getCameraOffset(camera.FieldOfView, extentsSize)
	local cameraRotation = camera.CFrame - camera.CFrame.p

	local instancePosition = instanceCFrame.p
	camera.CFrame = cameraRotation + instancePosition + (-cameraRotation.LookVector * cameraOffset)
	camera.Focus = cameraRotation + instancePosition
end

zoomToExtents(workspace.CurrentCamera, workspace.Baseplate)
65 Likes