Need help with having tank turret point at mouse

I am making a tank, and i am stuck at the part where i have to make the turret point at the mouse. I tried using hinges, motor6d, and vector 3 and nothing works. help

Could you group the turret barrels and the turret base into a group and then :SetPrimaryPartCFrame(CFrame.new(turret.Position, mouse.hit))

1 Like

This problem can get pretty tricky once you also have to account for signed values based on what quadrant you are in World space, but a solution can be to solve the problem in object space

local function GetYawAndPitchRequired(Origin: CFrame, Target: Vector3): (number, number)
   local originToTarget = Target - Origin.Position
   local transformedVector = Origin:VectorToObjectSpace(originToTarget)
   
   local distanceXZ = math.sqrt(transformedVector.X * transformedVector.X + transformedVector.Z * transformedVector.Z)

   -- Something about Roblox handling it's axes of direction differently, so some of the signs have to be flipped
   -- atan2 returns a value that's already signed, so that's less work for us
   local yaw = math.atan2(-transformedVector.X, -transformedVector.Z)
   local pitch = math.atan2(transformedVector.Y, distanceXZ)

   return yaw, pitch
end

We’d use this function like so

local turretCFrame = ...
local target = ...

local yawRequired, pitchRequired = GetYawAndPitchRequired(turretCFrame, target)
-- assuming you're using a hinge or a motor object for rotation
turret.Yaw.TargetAngle = yawRequired
-- if not, then you would probably have to do something like create a new CFrame based off on this value, and then lerp to it to do non-instantaneous movement

Uh ok so I used the code, but the servro dosnt turn heres my code:

		local mouse3D = game:GetService("ReplicatedStorage"):WaitForChild("mouse"..plr.Name).Value
		tankobj.mouselockconnection = Runservice.Heartbeat:Connect(function()
			local turretCFrame = model.gun.CFrame
			local yawRequired, pitchRequired = GetYawAndPitchRequired(turretCFrame, Vector3.new(mouse3D.X,mouse3D.Y,mouse3D.Z))
			model.Yaw.TargetAngle = yawRequired
		end)

the servo just dosnt move heres my code to update my mouse:

local mouse = game.Players.LocalPlayer:GetMouse()

game:GetService("RunService").RenderStepped:Connect(function()
	game.ReplicatedStorage:WaitForChild("mouse"..game.Players.LocalPlayer.Name).Value = mouse.Hit
end)

@WovenBreaker

Assuming there isn’t any other un-noticed issues within your code, it’s probably something to do with the servo not having enough torque or any other property related to servo movement.

I set my servo max torque to 900, and it still dosnt work. Heres my hinge/servo setup


the cyllinder is the gun, the square is the base
@WovenBreaker

I would suggest you change Torque to something near infinity, and are you sure your model isn’t anchored or has the attachments set up properly?

ok il set it to infinity Il come back when ready

It didnt work. Heres my file:
tank.rbxm.rbxl (47.6 KB)