local socket = require("socket") local maf = require 'maf' local vec3 = maf.vec3 local…
- User
local socket = require("socket")
local maf = require 'maf' local vec3 = maf.vec3 local quat = maf.quat
local samem = require 'SAMemory'
samem.require 'CVehicle' samem.require 'tHandlingData' samem.require 'CPlane' samem.require 'CTransmission'
-- Constants for controlling plane steering behavior local PITCH_UP_THRESHOLD = -15 -- Pitch angle threshold in degrees local FINE_STEERING_ANGLE = 135 -- Angle for fine steering adjustments in degrees local YAW_FACTOR = 0.1 -- Multiplicative factor for yaw adjustment local ROLL_FACTOR = 1 -- Multiplicative factor for roll adjustment local STEERING_SPEED = 5.0 -- Speed of steering control in units per second
-- Direction vectors local DIRECTION = { 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) }
-- Calculate the signed angle between two vectors with respect to a reference axis local function calculateSignedAngle(from, to, axis) local fromNormalized = from:clone():normalize() local toNormalized = to:clone():normalize() local dotProduct = fromNormalized:dot(toNormalized) local angle = math.acos(math.max(-1, math.min(1, dotProduct))) -- Clamp the dot product local crossProduct = fromNormalized:cross(toNormalized) local sign = crossProduct:dot(axis) < 0 and -1 or 1 return angle * sign end
-- Calculate the angle between two vectors in degrees local function calculateAngleBetweenVectors(v1, v2) local normV1, normV2 = v1:normalize(), v2:normalize() local dotProduct = math.max(-1, math.min(1, normV1:dot(normV2))) -- Clamp the dot product return math.deg(math.acos(dotProduct)) end
-- Obtain the conjugate of a quaternion local function conjugateQuaternion(q) return quat(-q.x, -q.y, -q.z, q.w) end
-- Compute the steering input for the plane to move towards a target position local function computeSteeringInput(plane, dt, targetPosition) local planePosition = vec3(getCarCoordinates(plane)) local planeRotation = quat(getVehicleQuaternion(plane))
local positionError = targetPosition - planePosition local localError = conjugateQuaternion(planeRotation) * positionError local errorDir = localError:normalize() local pitchError, rollError, yawError pitchError = vec3(0, localError.y, localError.z):normalize() rollError = vec3(localError.x, localError.y, 0):normalize() yawError = vec3(localError.x, 0, localError.z):normalize() local targetInput = vec3() local pitch = calculateSignedAngle(DIRECTION.FORWARD, pitchError, DIRECTION.RIGHT) if -pitch < PITCH_UP_THRESHOLD then pitch = (pitch + 360) % 360 end targetInput.x = pitch local angleError = calculateAngleBetweenVectors(DIRECTION.FORWARD, rollError) if angleError < FINE_STEERING_ANGLE then local yaw = -calculateSignedAngle(DIRECTION.FORWARD, yawError, DIRECTION.UP) targetInput.y = yaw * YAW_FACTOR else local roll = calculateSignedAngle(DIRECTION.UP, rollError, DIRECTION.FORWARD) targetInput.z = roll * ROLL_FACTOR end if math.abs(targetInput.y) < 0.025 then targetInput.y = 0 end 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)) local input = vec3() input.x = math.max(-1, math.min(1, input.x + (targetInput.x - input.x) * STEERING_SPEED * dt)) input.y = math.max(-1, math.min(1, input.y + (targetInput.y - input.y) * STEERING_SPEED * dt)) input.z = math.max(-1, math.min(1, input.z + (targetInput.z - input.z) * STEERING_SPEED * dt)) return input - Assistant
The issue you're encountering is a common problem in control systems known as "overshooting" or "oscillation." This occurs when a system overreacts to changes, causing it to swing back and forth around the target point instead of settling smoothly. This can be part of a broader set of issues related to control system tuning.
In the context of steering a plane towards a target, these oscillations often arise because the control inputs are too aggressive when the plane is close to the target, causing it to overshoot. Conversely, when the plane is far from the target, the control inputs might be too small, leading to slow convergence.
Here are some key terms you can research to address and understand this issue:
- User
так получается мне надо написать систему которая составит какой-то график и на его основе построить какую-то функцию для динамического изменения YAW_FACTOR
- Assistant
Да, создание системы управления, которая адаптирует управляющие факторы, такие как
YAW_FACTOR, в зависимости от текущих условий, может быть эффективным способом решения проблемы осцилляции и перерегулирования вашего самолета. Вот несколько шагов, которые могут быть полезны при разработке такой системы: - User
и как это можно реализовать в коде?
- Assistant
- User
а измени функцию adaptiveYawFactor чтобы она возвращала этот фактор пропорциональным углу ошибки. и чтобы мб как-нибудь пыталась гасить колебание? хз
- Assistant
- User
pitchError = vec3(0, localError.y, localError.z):normalize() rollError = vec3(localError.x, localError.y, 0):normalize() yawError = vec3(localError.x, 0, localError.z):normalize()
чем отличает ролл и йав еррор
- Assistant
Векторные ошибок
rollErrorиyawErrorпредставлены различными осями и компонентами, которые определяют поведение вращательного движения самолета относительно своей локальной системы координат.-
rollError(Ошибка крена):- Этот вектор определяет отклонения вокруг продольной оси самолета (оси, которая проходит от носа к хвосту).
- Составляется из компонентов
localError.xиlocalError.y, создавая вектор, лежащий в горизонтальной плоскости. - Его задача — выяснить, насколько сильно нужно наклонить крылья самолета влево или вправо для коррекции курса.
-
yawError(Ошибка рыскания):
-
- User
local function computeSteeringInput(plane, dt, targetPosition) local planePosition = vec3(getCarCoordinates(plane)) local planeRotation = quat(getVehicleQuaternion(plane))
local positionError = targetPosition - planePosition local localError = conjugateQuaternion(planeRotation) * positionError local errorDir = localError:normalize() local pitchError, rollError, yawError pitchError = vec3(0, localError.y, localError.z):normalize() rollError = vec3(localError.x, localError.y, 0):normalize() yawError = vec3(localError.x, 0, localError.z):normalize() local targetInput = vec3() local pitch = calculateSignedAngle(DIRECTION.FORWARD, pitchError, DIRECTION.RIGHT) if -pitch < PITCH_UP_THRESHOLD then pitch = (pitch + 360) % 360 end targetInput.x = pitch local angleError = calculateAngleBetweenVectors(DIRECTION.FORWARD, rollError) printStringNow(angleError - (angleError % 1), 10) if angleError < FINE_STEERING_ANGLE then local yaw = -calculateSignedAngle(DIRECTION.FORWARD, yawError, DIRECTION.UP) targetInput.y = yaw * 0.25 else local roll = calculateSignedAngle(DIRECTION.UP, rollError, DIRECTION.FORWARD) targetInput.z = roll * ROLL_FACTOR end if math.abs(targetInput.y) < 0.025 then targetInput.y = 0 end 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)) local input = vec3() input.x = math.max(-1, math.min(1, input.x + (targetInput.x - input.x) * STEERING_SPEED * dt)) input.y = math.max(-1, math.min(1, input.y + (targetInput.y - input.y) * STEERING_SPEED * dt)) input.z = math.max(-1, math.min(1, input.z + (targetInput.z - input.z) * STEERING_SPEED * dt)) return input - Assistant
Ваш код выглядит довольно близко к правильному, но есть несколько моментов, на которые стоит обратить внимание, чтобы удостовериться, что каждая ошибка используется согласно своему назначению. Давайте пройдемся по каждому шагу и проверим, правильно ли применяется каждая ошибка:
- User
- Assistant
- User
не, не используй отдельную функцию в коде. используя МАТЕМАТИЧЕСКУЮ функцию при рассчете фактора, понел
- Assistant