Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 2 years ago

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

Log in to vote
0
Answered by 2 years ago

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.

Ad

Answer this question