Making a servo motor point to MOUSE

Hello. I am trying to make a hingeconstraint that will change its target angle towards the mouse position. I have looked at other forums and have gotten this code.

if block.Config.Mouse.Value == true and block.Config.Servo.Value == true then
	local mouseposition
	while wait() do
		mouseposition = worldMouse(mouse.X,mouse.Y)
		-- define position of origin
		if mouseposition then
			local myX = (mouseposition.X - block:FindFirstChild("Base").Attachment_NO.WorldPosition.X)
			local myY = (mouseposition.Z - block:FindFirstChild("Base").Attachment_NO.WorldPosition.Z)
			local theta = math.atan2(myX, myY)
			block:FindFirstChild("Base").HingeConstraint.TargetAngle = math.deg(theta)


This code will only make the hinge point towards the mouse if it is on terrain or a basepart. I need code that can detect the mouse position even if it is pointed at nothing.

I make you a model:

What you want to make is raycast to the mouse from the camera, and if the raycast dont hit anithing, then remplaze the returning positin (nil) to the raycast origin + raycast direction * raycast range

ray.Origen + ray.Direction * rayRange

check this 5uphi post: Mouse.Hit vs Mouse.UnitRay - #6 by 5uphi

Thank you so much! There is one thing though. If the servo angle is at 359 and it hits 360 and goes back to 0, the servo motor will take the long way all the way back to 0 degrees instead of moving the one degree forward. How could I fix this?

i use your code in the testing model and i could not recreate the problem, all my output say the angle is between -180 and 180, i dont know how do you get an inssue, but you can try subtract the angle 180, so if you get 360 it will be 180 and if you get 0 it will -180 like the current output of the testing script

Is your problem in the testing model? becouse it could be the ownership of the part, maybe the local scritp inside the part will stop working when your character is too far away and it goes back to the original angle from the actual server