Rotating turret only on the y axis of the mouse

I originally got parts of the script from the devforum.

local uis = game:GetService('UserInputService')
local rus = game:GetService('RunService')

local model = script.Parent
local root = script.Root.Value
local pivot = script.Pivot.Value
local hinge = script.Hinge.Value

local function calculateServoAngle(hinge, targetPosition)
	local baseAttachment = hinge.Attachment1

	local object_horizontal_offset = (baseAttachment.WorldCFrame):PointToObjectSpace(targetPosition)
	local object_yaw_angle = math.atan2(object_horizontal_offset.Y, object_horizontal_offset.Z)
	object_yaw_angle = math.deg(object_yaw_angle)

	return object_yaw_angle
end

while wait(0.2) do
	local cam = workspace.CurrentCamera
	local mPos = uis:GetMouseLocation()
	local mRay = cam:ViewportPointToRay(mPos.Y, mPos.X)
	local rcr: RaycastResult? = workspace:Raycast(mRay.Origin, mRay.Direction*1e3)

	local mPosWorld: Vector3 = if rcr then rcr.Position else mRay.Origin+mRay.Direction*20
	print(mPosWorld)
	--local pitch = math.atan2(-pPitch.Z, pPitch.Y)
	
	--pitchHinge.TargetAngle = math.deg(pitch)
	--hinge.TargetAngle = -beta -- beta has to be negative so it points at you
	script.Remote.Value:FireServer(calculateServoAngle(hinge,mPosWorld))
end

It seems to only work with the y axis of the mouse and not the x axis.

And the provided demo works as intended but mine does not.

1 Like

Already getting closer.
Somehow the x and y was swapped and i fixed it.
But it still faces away from the mouse.
I want it to face to the mouse.

Okay fixed it.

I made the offset negative.

Sorry for trash post

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.