function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
code
-- Compute error vector transformed into local space
local error = targetPosition - planePosition;
error = -planeRotation * error; --transform into local space -- error = Quaternion.Inverse(plane.Rigidbody.rotation) * error;
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = error:normalize();
local pitchError = vec3(0, error.y, error.z):normalize();
local rollError = vec3(error.x, error.y, 0):normalize();
local yawError = vec3(error.x, 0, error.z):normalize();
-- Initialize target input vector
local targetInput = vec3();
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right);
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch;
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then -- if (Vector3.Angle(Vector3.forward, errorDir) < fineSteeringAngle) {
-- Calculate yaw adjustment -- local yaw = Vector3.SignedAngle(Vector3.forward, yawError, Vector3.up);
local yaw = signedAngle(dir.forward, yawError, dir.up); -- targetInput.y = yaw * yawFactor;
targetInput.y = yaw * yawFactor -- } else {
else -- local roll = Vector3.SignedAngle(Vector3.up, rollError, Vector3.forward);
-- Calculate roll adjustment -- targetInput.z = roll * rollFactor;
local roll = signedAngle(dir.up, rollError, dir.forward); -- }
targetInput.z = roll * rollFactor
end
-- Clamp inputs to range [-1, 1]
targetInput.x = math.max(-1, math.min(1, targetInput.x)) -- targetInput.x = Mathf.Clamp(targetInput.x, -1, 1);
targetInput.y = math.max(-1, math.min(1, targetInput.y)) -- targetInput.y = Mathf.Clamp(targetInput.y, -1, 1);
targetInput.z = math.max(-1, math.min(1, targetInput.z)) -- targetInput.z = Mathf.Clamp(targetInput.z, -1, 1);
-- Smoothly move towards the target input
-- local input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
-- lastInput = input;
return targetInput;
end
я переписал код изначально написанный для юнити.
вот оригинал
Vector3 CalculateSteering(float dt, Vector3 targetPosition) {
if (plane.Target != null && targetPlane.Health == 0) {
return new Vector3();
}
code
var error = targetPosition - plane.Rigidbody.position;
error = Quaternion.Inverse(plane.Rigidbody.rotation) * error; //transform into local space
var errorDir = error.normalized;
var pitchError = new Vector3(0, error.y, error.z).normalized;
var rollError = new Vector3(error.x, error.y, 0).normalized;
var yawError = new Vector3(error.x, 0, error.z).normalized;
var targetInput = new Vector3();
var pitch = Vector3.SignedAngle(Vector3.forward, pitchError, Vector3.right);
if (-pitch < pitchUpThreshold) pitch += 360f;
targetInput.x = pitch;
if (Vector3.Angle(Vector3.forward, errorDir) < fineSteeringAngle) {
var yaw = Vector3.SignedAngle(Vector3.forward, yawError, Vector3.up);
targetInput.y = yaw * yawFactor;
} else {
var roll = Vector3.SignedAngle(Vector3.up, rollError, Vector3.forward);
targetInput.z = roll * rollFactor;
}
targetInput.x = Mathf.Clamp(targetInput.x, -1, 1);
targetInput.y = Mathf.Clamp(targetInput.y, -1, 1);
targetInput.z = Mathf.Clamp(targetInput.z, -1, 1);
var input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
lastInput = input;
return input;
}
но в юнити другая система координат - направления отличаются от моих
local dir = {
forward = vec3(0, 1, 0), -- вперед
backward = vec3(0, -1, 0), -- назад
right = vec3(1, 0, 0), -- вправо
left = vec3(-1, 0, 0), -- влево
up = vec3(0, 0, 1), -- вверх
down = vec3(0, 0, -1) -- вниз
}
внеси в мой код изменения, которые адаптируют его под мою систему координат
Assistant
To adapt your code to match the different coordinate system, you need to adjust the directional vectors used in calculations involving the pitch, yaw, and roll. In Unity, the default coordinate system aligns as follows:
Forward: ( (0, 0, 1) )
Up: ( (0, 1, 0) )
Right: ( (1, 0, 0) )
Given your local directions:
Forward: ( (0, 1, 0) )
Up: ( (0, 0, 1) )
Right: ( (1, 0, 0) )
You need to remap the vectors in the CalculateSteeringForPlane function like this:
lua
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
-- Compute error vector transformed into local space
local error = targetPosition - planePosition;
error = -planeRotation * error;
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = error:normalize();
local pitchError = vec3(0, error.z, error.y):normalize();
local rollError = vec3(error.x, 0, error.y):normalize();
local yawError = vec3(error.x, error.z, 0):normalize();
-- Initialize target input vector
local targetInput = vec3();
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right);
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch;
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
-- Calculate yaw adjustment
local yaw = signedAngle(dir.forward, yawError, dir.up);
targetInput.y = yaw * yawFactor
else
-- Calculate roll adjustment
local roll = signedAngle(dir.up, rollError, dir.forward);
targetInput.z = roll * rollFactor
end
-- Clamp inputs to range [-1, 1]
targetInput.x = math.max(-1, math.min(1, targetInput.x))
targetInput.y = math.max(-1, math.min(1, targetInput.y))
targetInput.z = math.max(-1, math.min(1, targetInput.z))
-- Smoothly move towards the target input
-- local input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
-- lastInput = input;
return targetInput;
end
User
local maf = require 'maf'
local vec3 = maf.vector
local quat = maf.rotation
-- Порог для поднятия тангажа, используется для корректировки тангажа
local pitchUpThreshold = -15 -- значение в градусах, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Угол для тонкой корректировки рулевого управления,
-- определяет, когда следует выполнять корректировки рысканья или крена
local fineSteeringAngle = 5 -- значение в градусах, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Фактор для корректировки рысканья, множитель для настройки управления по рысканию
local yawFactor = 1 -- множитель, используется для масштабирования корректировки рысканья, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Фактор для корректировки крена, множитель для настройки управления по крену
local rollFactor = 0.01 -- множитель, используется для масштабирования корректировки крена, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Скорость рулевого управления, определяет, насколько быстро следует двигаться к целевому вводу
local steeringSpeed = 5.0 -- единиц в секунду, скорость перемещения к целевым значениям управления, извлечено из MonoBehaviour с fileID: 3737572916587997159
local dir = {
forward = vec3(0, 1, 0), -- вперед
backward = vec3(0, -1, 0), -- назад
right = vec3(1, 0, 0), -- вправо
left = vec3(-1, 0, 0), -- влево
up = vec3(0, 0, 1), -- вверх
down = vec3(0, 0, -1) -- вниз
}
function signedAngle(from, to, axis)
-- Step 1: Normalize the both vectors
local fromNormalized = from:clone():normalize()
local toNormalized = to:clone():normalize()
-- Step 2: Calculate the unsigned angle
local dotProduct = fromNormalized:dot(toNormalized)
local angle = math.acos(math.max(-1, math.min(1, dotProduct))) -- Clamp acos input
-- Step 3: Determine the sign using the cross product and reference axis
local crossProduct = fromNormalized:cross(toNormalized)
local sign = crossProduct:dot(axis) < 0 and -1 or 1
-- Step 4: Return the signed angle
return angle * sign
end
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
code
Assistant
The issue with the code not returning zeros as expected is likely related to how the target position is computed and how the transformations are handled.
Key Observations
Direction Calculation: The line local goPos = planeRotation * (dir.forward) projects the plane's forward direction in the world space, given its current rotation, but doesn't consider the current position of the plane. The resulting vector should give a world position that extends forward from the plane's current position, not just a direction.
Error Calculation: The target position should be relative to the plane's current position to properly calculate the steering angles as zero when the target is directly in front.
Modifications to Address the Issue
We must adjust goPos to be a position directly in front of the plane, not just a direction. This involves adding the direction to the plane's current position:
lua
function main()
local plane = storeCarCharIsInNoSave(playerPed)
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
-- Compute a point directly in front of the plane, not just a direction
local goPos = planePosition + planeRotation * dir.forward
print(CalculateSteeringForPlane(plane, 10, goPos))
end
Explanation
Translation Over Direction: By adding planeRotation * dir.forward to planePosition, goPos becomes a point in the world space that is directly in front of the plane. This adjustment ensures that when the plane is perfectly aligned forward towards goPos, the steering correction should indeed be zero.
Rotation Handling: Ensure that the rotation is correctly applied to achieve a consistent transformation of local to world space and vice versa.
This adjustment should correct the calculation so that when you call CalculateSteeringForPlane with this setup, the output should be very close to zero for all components, considering the function's logic and coordinate precision.
User
local maf = require 'maf'
local vec3 = maf.vector
local quat = maf.rotation
-- Порог для поднятия тангажа, используется для корректировки тангажа
local pitchUpThreshold = -15 -- значение в градусах, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Угол для тонкой корректировки рулевого управления,
-- определяет, когда следует выполнять корректировки рысканья или крена
local fineSteeringAngle = 5 -- значение в градусах, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Фактор для корректировки рысканья, множитель для настройки управления по рысканию
local yawFactor = 1 -- множитель, используется для масштабирования корректировки рысканья, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Фактор для корректировки крена, множитель для настройки управления по крену
local rollFactor = 0.01 -- множитель, используется для масштабирования корректировки крена, извлечено из MonoBehaviour с fileID: 3737572916587997159
-- Скорость рулевого управления, определяет, насколько быстро следует двигаться к целевому вводу
local steeringSpeed = 5.0 -- единиц в секунду, скорость перемещения к целевым значениям управления, извлечено из MonoBehaviour с fileID: 3737572916587997159
local dir = {
forward = vec3(0, 1, 0), -- вперед
backward = vec3(0, -1, 0), -- назад
right = vec3(1, 0, 0), -- вправо
left = vec3(-1, 0, 0), -- влево
up = vec3(0, 0, 1), -- вверх
down = vec3(0, 0, -1) -- вниз
}
function signedAngle(from, to, axis)
-- Step 1: Normalize the both vectors
local fromNormalized = from:clone():normalize()
local toNormalized = to:clone():normalize()
-- Step 2: Calculate the unsigned angle
local dotProduct = fromNormalized:dot(toNormalized)
local angle = math.acos(math.max(-1, math.min(1, dotProduct))) -- Clamp acos input
-- Step 3: Determine the sign using the cross product and reference axis
local crossProduct = fromNormalized:cross(toNormalized)
local sign = crossProduct:dot(axis) < 0 and -1 or 1
-- Step 4: Return the signed angle
return angle * sign
end
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
code
Assistant
The issue you're experiencing is likely due to a combination of factors related to vector normalization, angle computation, and potentially subtle differences in the numerical representation within your environment. Let's address these carefully.
Troubleshooting Steps
Quaternion Rotation: Ensure that the quaternion rotation is correctly applied to the direction vector to transform it to world space.
Angle Significance: Recheck your angle calculations in signedAngle and vec3.angle to ensure they provide an accurate representation of the relationship between vectors.
Error Vector Handling: Make sure that the transformation of the error vector into local space is accurate.
Detailed Checks
Quaternion and Error Handling:
Ensure that you are correctly using the rotation to transform vectors from world space to local space:
error calculation could be incorrectly flipping values due to the use of negative rotation.
Code Adjustments:
Verify that the signedAngle function is correctly computing the signed angle, especially with how it uses cross products and normalization.
Simplified Debugging:
Print intermediate results to verify computations at each stage and identify where the deviation occurs.
Code Review with Debugging
Let's add some debug prints to help diagnose the issue:
The debug outputs provide useful insights into the underlying calculations, indicating that there is an issue with how the error vector is being transformed and subsequently used. Let's break down the problem and suggest solutions:
Observations
Error Vector Transformation:
The world error vector seems reasonable, but the local error vector undergoes significant changes, especially in the x and y directions. This might be impacting the angle calculations leading to non-zero outputs.
Directional Error Vectors:
There is significant noise in the transformed error vector's components; these influence the resulting pitch, roll, and yaw errors.
Suggestions and Corrections
Quaternion Handling:
Ensure that -planeRotation correctly performs the transformation into local space. In some quaternion libraries, negating a quaternion might not produce the conjugate which is typically needed for transformations from world to local space.
lua
local errorLocal = planeRotation:inverse() * error
Verify that your library supports inverse(). If not, implement it manually using quaternion conjugation.
Precision Verification:
Examine whether the vectors are normalized accurately. When precision is critical, ensure both your quaternion transformation and vector math are precise.
Cross and Dot Products:
Investigate whether the cross and dot products used in signedAngle and vector normalization are sensitive to very small values, leading to outcomes influenced by computational inaccuracies.
Sensitivity to Fine Angles:
If pitch or yaw thresholds are too sensitive (fineSteeringAngle and pitchUpThreshold), then small deviations might lead to significant control inputs.
Code Adjustment with Debugging:
Use consistent debugging to identify whether adjustments fix the issue. Validate each new transformation approach:
lua
User
во первых - там нет функции inverse, есть только унарный минус. во вторых, откуда там берется такая огромная погрешность?
Assistant
Given your current setup and the absence of an inverse function in the quaternion library you're using, as well as the large discrepancy, let's explore potential solutions and explanations more thoroughly.
Quaternion Usage
Conjugate vs. Negation:
When only the unary minus is available, it might be performing a negation rather than computing a proper quaternion conjugate or inverse. This may lead to incorrect transformations from world to local space.
Quaternion Conjugate:
If -planeRotation is meant to reverse the transformation, ensure it behaves like a conjugate, typically computed by negating the imaginary parts (x, y, z) of the quaternion, not flipping all signs (w too).
Here's how you might manually compute the inverse given the standard quaternion form:
lua
local function quatConjugate(q)
return quat(q[1], -q[2], -q[3], -q[4])
end
Fine Steering and Error Amplification
Precision and Cumulative Error:
Small errors in transformation can accumulate and become significant when calculating angles, especially with high precision directional vectors.
Numerical Stability:
Transformations using quaternions are generally stable, but improper usage or inaccurate inversions can lead to larger-than-expected errors.
Steps to Address the Discrepancy
Calculate the Conjugate Manually:
Use the above quatConjugate function to adjust how you transform the error vector:
lua
local errorLocal = quatConjugate(planeRotation) * error
Review Vector Math:
Ensure all vector operations are performed correctly, especially normalization and dot/cross product calculations.
Precision & Debugging:
Thoroughly inspect intermediary steps with debugging statements, ensuring each component behaves as expected.
lua
User
и конжюгейт там тоже нет. ТОЛЬКО(!!!) унарный минус
Assistant
Given the constraints of your current environment with only the unary minus (-) available for quaternion operations, we'll need to carefully analyze how this operation is meant to work.
If the unary minus is intended to represent the inverse or conjugate in your math library, any mistakes in its implementation could lead to the discrepancies you're experiencing. Since typically a quaternion conjugate is used for reversing rotations, it involves negating only the vector part ((x, y, z)) and keeping (w) the same. The inverse of a unit quaternion (as it's often used in rotations) is the same as the conjugate because the quaternion is already normalized.
Steps to Troubleshoot and Adjust
Verify Quaternion Behavior:
Confirm that the unary minus correctly acts as a transform inverter, such as conjugation or inversion. If it negates the whole quaternion ((w, x, y, z)), it might not behave as expected for rotations.
Simulate Conjugation Manually:
If you can't directly alter how -planeRotation works internally, you'll need to simulate the conjugate behavior by manually working with the vector components.
Testing Alternative Logic
If -planeRotation isn't behaving as expected, let's try manipulating the transformation logic to test if you can achieve the expected behavior with available tools. Although you only have unary minus, ensuring that the transformation back into local space acts correctly is crucial here.
Assume the math library treats - correctly for transformations but just doesn't document it as a conjugate. We'll adjust as follows:
lua
Not yet included in a published release.
Changes made:
Changed the order of components while defining pitchError, rollError, and yawError.
This modification ensures the correct mapping between your vector definitions and Unity's system, making sure the directional calculations accurately represent the desired steering behavior for pitch, yaw, and roll.
-- Compute error vector transformed into local space
local error = targetPosition - planePosition;
error = -planeRotation * error;
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = error:normalize();
local pitchError = vec3(0, error.z, error.y):normalize();
local rollError = vec3(error.x, 0, error.y):normalize();
local yawError = vec3(error.x, error.z, 0):normalize();
-- Initialize target input vector
local targetInput = vec3();
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right);
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch;
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
-- Calculate yaw adjustment
local yaw = signedAngle(dir.forward, yawError, dir.up);
targetInput.y = yaw * yawFactor
else
-- Calculate roll adjustment
local roll = signedAngle(dir.up, rollError, dir.forward);
targetInput.z = roll * rollFactor
end
-- Clamp inputs to range [-1, 1]
-- targetInput.x = math.max(-1, math.min(1, targetInput.x))
-- targetInput.y = math.max(-1, math.min(1, targetInput.y))
-- targetInput.z = math.max(-1, math.min(1, targetInput.z))
-- Smoothly move towards the target input
-- local input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
-- lastInput = input;
return targetInput;
end
function main()
local plane = storeCarCharIsInNoSave(playerPed)
code
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
local goPos = planeRotation * (dir.forward)
print(CalculateSteeringForPlane(plane , 10, goPos ))
end
почему этот код возвращает [ML] (script) (^^)tracers.lua: (-1.596023, -1.626833, 0.000000)
если должен возвращать нули? (вектор РОВНО вперед относительно самолета)
-- Compute error vector transformed into local space
local error = targetPosition - planePosition;
error = -planeRotation * error;
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = error:normalize();
local pitchError = vec3(0, error.z, error.y):normalize();
local rollError = vec3(error.x, 0, error.y):normalize();
local yawError = vec3(error.x, error.z, 0):normalize();
-- Initialize target input vector
local targetInput = vec3();
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right);
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch;
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
-- Calculate yaw adjustment
local yaw = signedAngle(dir.forward, yawError, dir.up);
targetInput.y = yaw * yawFactor
else
-- Calculate roll adjustment
local roll = signedAngle(dir.up, rollError, dir.forward);
targetInput.z = roll * rollFactor
end
-- Clamp inputs to range [-1, 1]
-- targetInput.x = math.max(-1, math.min(1, targetInput.x))
-- targetInput.y = math.max(-1, math.min(1, targetInput.y))
-- targetInput.z = math.max(-1, math.min(1, targetInput.z))
-- Smoothly move towards the target input
-- local input = Vector3.MoveTowards(lastInput, targetInput, steeringSpeed * dt);
-- lastInput = input;
return targetInput;
end
function main()
local plane = storeCarCharIsInNoSave(playerPed)
code
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
local goPos = planePosition + planeRotation * dir.forward
print(CalculateSteeringForPlane(plane , 10, goPos ))
end
почему этот код возвращает [ML] (script) (^^)tracers.lua: (1.574537, -1.583847, 0.000000)
если должен возвращать нули? (вектор РОВНО вперед относительно самолета)
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
-- Compute error vector transformed into local space
local error = targetPosition - planePosition
local errorTransformed = -planeRotation * error -- This step may introduce inaccuracies
print("Error (world):", error)
print("Error (local):", errorTransformed)
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = error:normalize()
local pitchError = vec3(0, errorTransformed.z, errorTransformed.y):normalize()
local rollError = vec3(errorTransformed.x, 0, errorTransformed.y):normalize()
local yawError = vec3(errorTransformed.x, errorTransformed.z, 0):normalize()
print("PitchError:", pitchError)
print("RollError:", rollError)
print("YawError:", yawError)
-- Initialize target input vector
local targetInput = vec3()
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right)
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
-- Calculate yaw adjustment
local yaw = signedAngle(dir.forward, yawError, dir.up)
targetInput.y = yaw * yawFactor
else
-- Calculate roll adjustment
local roll = signedAngle(dir.up, rollError, dir.forward)
targetInput.z = roll * rollFactor
end
-- Clamp inputs to range [-1, 1]
-- targetInput.x = math.max(-1, math.min(1, targetInput.x))
-- targetInput.y = math.max(-1, math.min(1, targetInput.y))
-- targetInput.z = math.max(-1, math.min(1, targetInput.z))
return targetInput
end
Potential Issues & Adjustments
Quaternion Conjugate/Negation Issue: The negation of the quaternion -planeRotation might result in unexpected behavior depending on how quaternion negation is handled in your math library.
Ensure quaternion inversion is correct if applying transformation back to local from world space.
Direction Vector Orientation: Verify that the direction vectors correctly represent forward, sideways, and up directions in your environment.
Normalization Check: Ensure that all vectors are properly normalized before using them in calculations like dot and cross.
If you still encounter issues, consider explicitly walking through the vector math with a known set of inputs to manually confirm expected behavior at each step.
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
-- Get current position and orientation of the plane
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
-- Correct the error transformation
local error = targetPosition - planePosition
local errorLocal = planeRotation:inverse() * error -- Assuming inverse() or similar function exists
-- Print debug information
print("Error (world):", error)
print("Error (local):", errorLocal)
-- Normalize directional errors for pitch, roll, and yaw
local errorDir = errorLocal:normalize()
local pitchError = vec3(0, errorLocal.z, errorLocal.y):normalize()
local rollError = vec3(errorLocal.x, 0, errorLocal.y):normalize()
local yawError = vec3(errorLocal.x, errorLocal.z, 0):normalize()
print("PitchError:", pitchError)
print("RollError:", rollError)
print("YawError:", yawError)
-- Initialize target input vector
local targetInput = vec3()
-- Compute pitch based on error and thresholds
local pitch = signedAngle(dir.forward, pitchError, dir.right)
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch
-- Determine steering adjustments for yaw or roll
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
-- Calculate yaw adjustment
local yaw = signedAngle(dir.forward, yawError, dir.up)
targetInput.y = yaw * yawFactor
else
-- Calculate roll adjustment
local roll = signedAngle(dir.up, rollError, dir.forward)
targetInput.z = roll * rollFactor
end
-- Return the calculated input
return targetInput
end
These checks and changes focus on ensuring that the error transformation and resulting calculations are consistent and accurate for your coordinate settings, enabling zero values when expected.
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
local error = targetPosition - planePosition
local errorLocal = quatConjugate(planeRotation) * error
print("Error (world):", error)
print("Error (local):", errorLocal)
-- Normalize the error
local errorDir = errorLocal:normalize()
local pitchError = vec3(0, errorLocal.z, errorLocal.y):normalize()
local rollError = vec3(errorLocal.x, 0, errorLocal.y):normalize()
local yawError = vec3(errorLocal.x, errorLocal.z, 0):normalize()
print("PitchError:", pitchError)
print("RollError:", rollError)
print("YawError:", yawError)
local targetInput = vec3()
local pitch = signedAngle(dir.forward, pitchError, dir.right)
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
local yaw = signedAngle(dir.forward, yawError, dir.up)
targetInput.y = yaw * yawFactor
else
local roll = signedAngle(dir.up, rollError, dir.forward)
targetInput.z = roll * rollFactor
end
return targetInput
end
Carefully verifying the quaternion operations and error propagation should help address the unexpected results you're seeing.
function CalculateSteeringForPlane(plane ,--[[float]] dt, --[[Vector3]] targetPosition)
local planePosition = vec3(getCarCoordinates(plane))
local planeRotation = quat(getVehicleQuaternion(plane))
-- Calculate the error (direct difference, verify if we need transformation)
local error = targetPosition - planePosition
-- Suppose unary minus acts as conjugation; use it
local errorLocal = -planeRotation * error
print("Error (world):", error)
print("Error (local):", errorLocal)
-- For stability, recheck that these normalized vectors are close to expected results
local errorDir = errorLocal:normalize()
local pitchError = vec3(0, errorLocal.z, errorLocal.y):normalize()
local rollError = vec3(errorLocal.x, 0, errorLocal.y):normalize()
local yawError = vec3(errorLocal.x, errorLocal.z, 0):normalize()
print("PitchError:", pitchError)
print("RollError:", rollError)
print("YawError:", yawError)
local targetInput = vec3()
local pitch = signedAngle(dir.forward, pitchError, dir.right)
if (-pitch < pitchUpThreshold) then
pitch = pitch + 360
end
targetInput.x = pitch
if (vec3.angle(dir.forward, errorDir) < fineSteeringAngle) then
local yaw = signedAngle(dir.forward, yawError, dir.up)
targetInput.y = yaw * yawFactor
else
local roll = signedAngle(dir.up, rollError, dir.forward)
targetInput.z = roll * rollFactor
end
return targetInput
end
Additional Steps
Debugging Library Implementation:
Investigate how - is implemented in the library to ensure it aligns with expected quaternion behavior.
Verify if there are alternative functions not documented widely but existing in source code or examples.
Testing Inputs:
Test with known simple inputs manually computed to verify if the transition to local space truly results in expected (0) vectors.
These considerations and checks should help pin down whether the entire error transformation logic or quaternion handling is causing discrepancies. If the library does not support operations beyond - in a useful way, consider writing a small utility function for expected quaternion manipulations if adjustable in your context.