I have gun turrets which are attached to a plane model via HingeConstraints. There is a hinge to control the turret base (horizontal rotation) and a hinge to control the gun barrel (vertical rotation).
Everything works just fine with the turret rotating towards the mouse position using the code below, the issue comes when the plane which the turrets are attached to pitches up or down, ascending or descending.
local turret = gun.gun
local turretBase = turret.GunModel.TurretBase
local turretServo = turret.GunModel.TurretTop.HorizontalRotator
local barrelAttachment = turret.GunModel.Glass.Attachment0
local barrelServo = turret.GunModel.Glass.VerticalRotator
--===================
-- HORIZONTAL ROTATE
--===================
local function GetYawAngle(targetPos, basePart)
local turretOrigin = basePart.Position
local turretForward = basePart.CFrame.LookVector
local toTarget = (targetPos - turretOrigin).Unit
-- Project to XZ plane for yaw
turretForward = Vector3.new(turretForward.X, 0, turretForward.Z).Unit
toTarget = Vector3.new(toTarget.X, 0, toTarget.Z).Unit
local dot = turretForward:Dot(toTarget)
local angle = math.acos(math.clamp(dot, -1, 1))
-- Determine sign using cross product
if turretForward:Cross(toTarget).Y < 0 then
angle = -angle
end
return -math.deg(angle)
end
--=================
-- VERTICAL ROTATE
--=================
local function GetPitchAngle(targetPos, attachment)
local origin = attachment.WorldPosition
local toTarget = (targetPos - origin).Unit
local localTarget = attachment.WorldCFrame:VectorToObjectSpace(toTarget)
-- Angle between forward (-Z) and aim vector
return math.deg(math.atan2(localTarget.Y, -localTarget.Z))
end
function script.aim.OnServerInvoke(player,mouseHit)
local targetPos =mouseHit.Position
turretServo.TargetAngle = GetYawAngle(targetPos, turretBase)
barrelServo.TargetAngle = GetPitchAngle(targetPos, barrelAttachment)
end
When flying level, the aim is aligned like so:
https://gyazo.com/9a31e3054ec0f54bd944dc5722f69d12
But when climbing, it goes off to the side, as if the hinges are aiming towards where the mouse would be if the plane were level:
https://gyazo.com/9a31e3054ec0f54bd944dc5722f69d12
I have tried both world-relative and part-relative positions/orientations and both have the exact same issue. Any help would be greatly appreciated.