Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I convert mouse.hit to hinge.Target Angle?

So I'm currently scripting a tank. I'm trying to make a turret that rotates with two hinges. One at the base, and one at the gun, I want the turret to rotate the gun and base with the player's mouse. I don't know how to get the target angle for the hinge constraint.

I'm trash at positional math and I've been scouring the internet to see if anyone else has done it.

Please help!

What I have: Right now the player sits in the gun of the tank. The camera is locked to a part behind the player set to move with the gun(Via weld).

Camera Code:

local function run_camera()
	workspace.CurrentCamera.CFrame = tank.Parts.Camera_Part.CFrame
end

do
	workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable			 
        runService:BindToRenderStep("run_Cam",200,run_camera)
end

Here is what I have for the turret:

I'm trying to set the TargetAngle to be where the mouse is pointing, so the turret base rotates to the mouse position.

local function run_Tank_Turret()
	local camera = workspace.CurrentCamera
	local base_hinge = tank.Constraints.Turret.Base_Hinge
	local gun_hinge = tank.Constraints.Turret.Gun_Hinge
	local delta = mouse.Hit.Position - tank.PrimaryPart.CFrame.Position
	base_hinge.TargetAngle = math.deg(math.atan2(-delta.Z, delta.X))
end

do
	workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable
	runService:BindToRenderStep("run_Cam",200,run_camera)
	runService:BindToRenderStep("run_Tank_Turret",300,run_Tank_Turret)
end

I have no experience with trigonometry. Hence why I can't calculate the target angle from mouse.hit

Also, I currently have no code for the verticle gun, but I'll cross that bridge when I get there.

1 answer

So I found out the answer. I stumbled across this post: https://devforum.roblox.com/t/turret-rotation-using-hingeconstraint-servo/1244664/6

nicemike40 mentioned that OP might need to mess with the positives and the negatives so I found an equation that works for :

local delta = mouse.Hit.Position - tank.MovingParts.Turret.Base.CFrame.Position
base_hinge.TargetAngle = -math.deg(math.atan2(-delta.Z, delta.X))+90

I needed to make -math.deg(math.atan2(-delta.Z, delta.X))+90 negative then add 90 degrees to the final angle. It works now.

This discussion is preserved as it was. New answers, comments, and votes are closed.