Need help with trigonometry for Motor6D FollowSpot light

I’m working on a light that realistically follows a player from where it is. To achieve this, I’m using (what should be) basic trig to calculate the desired angle for my Motor6D. However, since each dimension needs to be handled separately by the light (the clamp turns for the X and Z dimension and the light turns for the Y dimension), the math is coming out weirdly.

Below I’ve attached a video — the white lines are helper lines, the green line is where the light is currently pointing, and the blue line is where the light should ideally end up pointing.

If anyone could help me correct the math, I’d appreciate it.

Update: this is fixed now. Thanks for no help!

local light = script.Parent
local spotlight = light.SpotLight
local clamp = light.Clamp
local clampBase = clamp.Base
local clampUp = clamp.Up
local clampRight = clamp.Right

local targetPosition = Vector3.new(0, 10, 0)

function clampToVector(vector3)
local vector = vector3 - clampBase.Position

local vectorAngle = math.atan2(vector.Z, vector.X)
local vectorLength = math.sqrt(vector.X ^ 2 + vector.Z ^ 2)

local clampUpAngle = math.atan2(clampUp.CFrame.UpVector.Y, clampUp.CFrame.UpVector.Z)
local clampUpLength = math.sqrt(clampUp.CFrame.UpVector.Y ^ 2 + clampUp.CFrame.UpVector.Z ^ 2)

local clampRightAngle = math.atan2(clampRight.CFrame.RightVector.X, clampRight.CFrame.RightVector.Y)
local clampRightLength = math.sqrt(clampRight.CFrame.RightVector.X ^ 2 + clampRight.CFrame.RightVector.Y ^ 2)

clamp.CFrame = CFrame.new(clampBase.Position, clampBase.Position + Vector3.new(math.cos(vectorAngle), 0, math.sin(vectorAngle)) * vectorLength) * CFrame.Angles(0, 0, clampUpAngle - clampRightAngle) * CFrame.Angles(math.pi / 2, 0, 0)

end

function spotlightToVector(vector3)
local vector = vector3 - clampBase.Position

local vectorAngle = math.atan2(vector.Y, vector.X)
local vectorLength = math.sqrt(vector.X ^ 2 + vector.Y ^ 2)

spotlight.CFrame = CFrame.new(clamp.CFrame:toObjectSpace(clampBase.Position), clamp.CFrame:toObjectSpace(clampBase.Position + Vector3.new(math.cos(vectorAngle), math.sin(vectorAngle