SA:MP Lua [LUA] Anti-Rollover

Niourozi

Новичок
Автор темы
20
20
Версия SA-MP
  1. Любая
Wrote a small script that prevents your car from rolling over. How it works: the script directly corrects the angular velocity of the vehicle — no teleportation, no sudden visual effects.


Works with all car types. Motorcycles, planes, helicopters and RC vehicles are excluded automatically.


Activation: automatic.


Autor: Niourozi (me)

v1.1 update

- Added wheel contact detection using CVehicle suspension offsets (smooth copy at base+0x4B0).
Reads all 4 wheel compression values each tick to confirm how many wheels are actually
off the ground before acting, instead of relying solely on upZ + rightZ.

- Rollover detection split into 3 stages:
TIPPING (upZ < 0.65) → light turn speed damping
FLIPPED (upZ < 0.20, 3+ wheels up) → strong damping + corrective angular impulse
INVERTED (upZ < 0) → full matrix recovery

- Full flip recovery for completely inverted vehicles: rewrites the rotation matrix to
upright preserving the current heading, zeroes angular velocity, dampens linear speed,
and lifts the car slightly to avoid immediate ground re-collision. Triggers on the
first tick upZ goes below 0 so the engine doesn't accumulate collision damage.

- Tick rate reduced from 30ms to 25ms.
- Per-stage cooldowns instead of a single global one (100 / 200 / 800ms).

v1.2 update

 

Вложения

  • AntiRollover.lua
    4.9 KB · Просмотры: 15
  • AntiRollover (1.1).lua
    5.8 KB · Просмотры: 7
  • AntiRollover (1.2).lua
    9.2 KB · Просмотры: 10
Последнее редактирование:
  • Нравится
Реакции: falambons и B365

Niourozi

Новичок
Автор темы
20
20
Почему на английском шутки смешнее?
Так красиво написано, а по сути автофлип

fair point lol, 1.1 recovery was basically just a snap — deserved the autoflip label

pushed 1.2 with a proper rework, here's what changed:

gradual recovery instead of rewriting the rotation matrix in one tick, it now lerps the forward/right/up vectors toward the target upright orientation over 65 or 90 ticks depending on whether the car is moving. each tick it re-orthonormalizes them via cross product so the matrix doesn't go skewed mid-interpolation. the car visually rotates back to upright smoothly instead of snapping.

dynamic recovery ticks recovery duration is now picked at flip-start by sampling the velocity magnitude. if the car is moving (above a small threshold) it uses 90 ticks, if it's stationary it uses 65. gives a smoother result at high speed without dragging out the recovery when the car is already still.

velocity preserved through the lift setCarCoordinates was zeroing out the linear velocity internally — the engine resets physics state on any position change. fixed by saving XY velocity right before the call and writing it back immediately after. vz gets clamped to zero from below so the car doesn't carry negative fall velocity into the upright state.

lift timing the z lift only fires at t=0.5, when the matrix is already ~50% corrected. reduces the snap compared to 1.1.

teleport is still there, just delayed and smaller can't fully remove it — without lifting the car off the ground it just re-collides immediately and interrupts the recovery. open to cleaner approaches.

added raknetSendRpc(103) before setCarCoordinates some servers fire a ClientCheck when they detect a sudden position delta. sending rpc 103 right before the coord change makes it look like a normal check response cycle rather than a naked teleport. not foolproof but helps on strict servers.

removed COOLDOWN_INVERTED (800ms) didn't make sense anymore. the recovery runs its own tick loop and blocks new triggers via recovery.active, so a hardcoded cooldown on top was just redundant.

config cleanup removed INVERT_LIFT and INVERT_DAMP. replaced with RECOVERY_TICKS_MOVING, RECOVERY_TICKS_STILL, MOVING_THRESHOLD and RECOVERY_Z_LIFT.
 

Вложения

  • AntiRollover (1.2).lua
    9.2 KB · Просмотры: 9
Последнее редактирование:

Порожденный

Активный
383
64
Справедливое замечание, лол, восстановление в версии 1.1 было практически мгновенным — оно заслужило метку «автопереворот».

Выпущена версия 1.2 с полноценной переработкой, вот что изменилось:

Вместо перезаписи матрицы вращения за один тик, теперь происходит постепенное восстановление: векторы вперед/вправо/вверх интерполируются в направлении целевой вертикальной ориентации в течение 65 или 90 тиков в зависимости от того, движется ли автомобиль. На каждом тике происходит их реортонормализация с помощью векторного произведения, чтобы матрица не искажалась в процессе интерполяции. Визуально автомобиль плавно возвращается в вертикальное положение, а не резко останавливается.

Динамическое восстановление: продолжительность восстановления теперь определяется в момент старта путем выборки величины скорости. Если автомобиль движется (выше небольшого порогового значения), используется 90 тактов, если он неподвижен — 65. Это обеспечивает более плавный результат на высоких скоростях, не затягивая восстановление, когда автомобиль уже стоит на месте.

Сохранение скорости при использовании функции setCarCoordinates приводило к внутреннему обнулению линейной скорости — движок сбрасывает физическое состояние при любом изменении положения. Проблема была решена путем сохранения скорости по осям XY непосредственно перед вызовом функции и ее немедленной записи после него. Скорость по осям vz ограничивается нулем снизу, чтобы автомобиль не переносил отрицательную скорость падения в вертикальное положение.

Синхронизация подъема по оси Z происходит только при t=0,5, когда матрица уже скорректирована примерно на 50%. Это уменьшает момент срабатывания по сравнению с версией 1,1.

Телепортация всё ещё существует, просто происходит с задержкой, и её нельзя полностью удалить — без поднятия машины с земли она немедленно столкнётся снова и прервёт восстановление. Открыт для более чистых подходов.

Добавлена функция raknetSendRpc(103) перед setCarCoordinates. Некоторые серверы запускают ClientCheck при обнаружении внезапного изменения положения. Отправка RPC 103 непосредственно перед изменением координат создает впечатление обычного цикла ответа проверки, а не просто телепортации. Это не гарантирует полной защиты, но помогает на серверах со строгими требованиями.

Удалено значение COOLDOWN_INVERTED (800 мс), оно больше не имело смысла. Восстановление запускает собственный цикл обработки событий и блокирует новые триггеры через recovery.active, поэтому жестко заданное время восстановления было просто излишним.

В результате очистки конфигурации были удалены INVERT_LIFT и INVERT_DAMP. Они заменены на RECOVERY_TICKS_MOVING, RECOVERY_TICKS_STILL, MOVING_THRESHOLD и RECOVERY_Z_LIFT.
Too much text, proper long day