I’m working on an Autopilot/Auto-controlled aircraft and need some help with the guidance system. Currently, I’m having issues with the Position Guidance where the aircraft behaves unpredictably and unreliably when attempting to guide towards a target Vector3 Position, almost moving randomly. This is of course made a lot more difficult since I am attempting to rotate the aircraft using an AngularVelocity.
This is the main part of the code
local com = script.Parent.Parent.CentreOfMass
local aiControl = script.Parent.Parent.AI_CONTROL
local function controlSurfaceGuidance(roll, pitch, yaw)
aiControl.AI_ROLL.Value = roll
aiControl.AI_PITCH.Value = pitch
aiControl.AI_YAW.Value = yaw
end
local function positionGuidance()
local currentPosition = com.Position
local currentLookVector = com.CFrame.LookVector
-- Calculate direction
local directionToTarget = (aiControl.AI_NAV.Value - currentPosition).Unit
-- Calculate roll
local rightVector = com.CFrame.RightVector
local rollDifference = directionToTarget:Dot(rightVector)
local rollControl = math.clamp(-rollDifference * 2, -1, 1)
-- Calculate pitch
local verticalDifference = directionToTarget:Dot(Vector3.new(0, 1, 0)) - currentLookVector:Dot(Vector3.new(0, 1, 0))
local pitchControl = math.clamp(-verticalDifference * 2, -1, 0) -- Avoid pitching down
-- Apply roll and pitch
controlSurfaceGuidance(rollControl, pitchControl, 0)
-- Check if the aircraft is close
if (aiControl.AI_NAV.Value - currentPosition).Magnitude <= 5 then
print("Target Position Reached")
end
end
while wait() do
positionGuidance()
end
The positionGuidance() function gives 3 axes values which are put in to the controlSurfaceGuidance() function to assign those values to 3 Number values clamped between -1 and +1. Those 3 Number values are then put into the code for the AngularVelocity which isn’t included above, but you get the gist. The rotation code works fine, just the calculations of how to turn the aircraft.