RLS Studios
ProjectsPatreonCommunityDocsAbout
Join Patreon
BeamNG Modding Docs

Guides

Reference

Server CommandsGE UtilitiesGame Engine MainNavigation GraphScreenshot CaptureServerServer ConnectionSpawnpoint ManagerSimulation TimeVehicle SpawningSuspension Frequency Tester
Gameplay AchievementGameplay CityDiscoverForce FieldGarage ModeMarker InteractionParking SystemGameplay Playmode MarkersGameplay PoliceGameplay RallyGameplay Rally LoopGameplay Raw POIsGameplay Skidpad TestSpeed Trap LeaderboardsSpeed Traps and CamerasGameplay StatisticsTaxi Ride SystemTraffic SystemVehicle PerformanceWalking

UI

Resources

BeamNG Game Engine Lua Cheat SheetGE Developer RecipesMCP Server Setup

// RLS.STUDIOS=true

Premium Mods for BeamNG.drive. Career systems, custom vehicles, and immersive gameplay experiences.

Index

HomeProjectsPatreon

Socials

DiscordPatreon (RLS)Patreon (Vehicles)

© 2026 RLS Studios. All rights reserved.

Modding since 2024

API ReferenceGE Extensionsgameplay

Traffic System

Reference for `gameplay_traffic`, the master traffic system that spawns, manages, respawns, and pools AI traffic vehicles. This is the central orchestrator for all traffic behavior.

Reference for gameplay_traffic, the master traffic system that spawns, manages, respawns, and pools AI traffic vehicles. This is the central orchestrator for all traffic behavior.


Module Exports (M)

Setup & Lifecycle

FunctionSignatureDescription
setupTraffic(amount?, policeRatio?, options?) → boolPrepares vehicle groups and spawns traffic
setupTrafficWaitForUi(usePolice?)Setup from radial menu with loading screen
setupCustomTraffic(amount?, params?)Spawns traffic with custom multiSpawn params
spawnTraffic(amount?, groupData?, options?)Low-level spawn via core_multiSpawn
activate(vehList?, ignoreFilter?)Activates traffic mode for given vehicle IDs
deactivate(stopAi?)Deactivates traffic for all vehicles
toggle(keepInMemory?)Toggles traffic on/off in freeroam
deleteVehicles()Deletes all traffic vehicles

Vehicle Management

FunctionSignatureDescription
insertTraffic(id, ignoreAi?, ignoreVehPool?)Inserts vehicle into traffic table
removeTraffic(id, stopAi?)Removes vehicle from traffic table
refreshVehicles()Resets core data on all traffic vehicles

Focus & Teleporting

FunctionSignatureDescription
setFocus(mode?, data?)Sets focus point ("camera", "vehicle", or "custom")
getFocus() → tableReturns current focus point data
forceTeleport(id, pos?, dir?, minDist?, maxDist?, targetDist?)Force-teleports a traffic vehicle
scatterTraffic(vehIds?, minDist?, maxDist?)Teleports a group of vehicles away

State & Config

FunctionSignatureDescription
getState() → stringReturns "off", "loading", "spawning", or "on"
getTrafficVars() → tableReturns current traffic variables
setTrafficVars(data, reset?)Sets variables like aiMode, speedLimit, activeAmount
setActiveAmount(amount?)Sets max visible vehicles
setDebugMode(value)Toggles debug visualization

Queries

FunctionSignatureDescription
getTrafficData() → tableReturns the full traffic table (id → vehicle object)
getTraffic() → tableAlias for getTrafficData
getTrafficList() → tableReturns list of AI traffic vehicle IDs
getTrafficAiVehIds() → tableAlias for getTrafficList
getTrafficAmount(activeOnly?) → numberReturns traffic vehicle count
getNumOfTraffic(activeOnly?) → numberAlias for getTrafficAmount
getTrafficPool() → poolReturns the vehicle active pooling object
getIdealSpawnAmount(amount?, ignoreAdjust?) → numberCalculates how many vehicles to spawn
freezeState() → trafficData, policeData, parkingDataSerializes traffic + police + parking state
unfreezeState(trafficData, policeData, parkingData)Restores traffic + police + parking state

Aliases

FunctionSignatureDescription
forceTeleportAll(vehIds?, minDist?, maxDist?)Alias for scatterTraffic
trackAIAllVeh(mode?)Sets AI mode for all traffic vehicles (called from radial menu)

Hooks / Lifecycle

FunctionDescription
onUpdateMain per-frame loop: focus updates, pool management, traffic logic
onPreRenderDebug visualization (lines, text) when debugMode is on
onVehicleMapmgrUpdateCompletes spawn process when last vehicle processes mapmgr
onVehicleSpawnedUpdates traffic role/properties on vehicle replace
onVehicleSwitchedChecks if new player vehicle should join traffic table
onVehicleResettedRe-checks player vehicle data
onVehicleDestroyedRemoves vehicle from traffic
onVehicleActiveChangedHandles teleport flags when vehicles activate/deactivate in pool
onVehicleGroupSpawnedActivates traffic after multiSpawn completes
onTrafficStartedInternal: initializes pool, focus, variables
onTrafficStoppedInternal: cleans up pool and tables
onClientStartMissionSets worldLoaded flag
onClientEndMissionFull reset of traffic system
onUiWaitingStateCallback for loading UI - triggers parking + traffic setup
onSerializeSerializes traffic state for hot-reload
onDeserializedRestores traffic state after hot-reload

Module Fields

FieldTypeDefaultDescription
debugModeboolfalseVisual and logging debug mode
showMessagesbooltrueWhether UI messages can be automatically shown
forceFocusboolnilForces focus updates even when traffic is off
M.activate(vehList, ignoreFilter)-activate handler
M.deactivate(stopAi)-deactivate handler
M.debugModevalue-visual and logging debug mode
M.deleteVehicles()-deleteVehicles handler
M.dependenciesvalue-Returns list of extension dependencies
M.forceTeleport(id, pos, dir, minDist, maxDist, targetDist)-forceTeleport handler
M.forceTeleportAll(vehIds, minDist, maxDist)-forceTeleportAll handler
M.freezeState()-freezeState handler
M.getFocus()-Returns Focus
M.getIdealSpawnAmount(amount, ignoreAdjust)-Returns IdealSpawnAmount
M.getNumOfTraffic(activeOnly)-Returns NumOfTraffic
M.getState()-Returns State
M.getTraffic()-Returns Traffic
M.getTrafficAiVehIds()-Returns TrafficAiVehIds
M.getTrafficAmount(activeOnly)-Returns TrafficAmount
M.getTrafficData()-Returns TrafficData
M.getTrafficList()-Returns TrafficList
M.getTrafficPool()-Returns TrafficPool
M.getTrafficVars()-Returns TrafficVars
M.insertTraffic(id, ignoreAi, ignoreVehPool)-insertTraffic handler
M.onClientEndMission()-Callback for ClientEndMission event
M.onClientStartMission()-Callback for ClientStartMission event
M.onDeserialized(data)-Callback for Deserialized event
M.onPreRender(dt)-Callback for PreRender event
M.onSerialize()-Callback for Serialize event
M.onTrafficStarted()-Callback for TrafficStarted event
M.onTrafficStopped()-Callback for TrafficStopped event
M.onUiWaitingState()-Callback for UiWaitingState event
M.onUpdate(dtReal, dtSim)-Callback for Update event
M.onVehicleActiveChanged(vehId, active)-Callback for VehicleActiveChanged event
M.onVehicleDestroyed(id)-Callback for VehicleDestroyed event
M.onVehicleGroupSpawned(vehList, groupId, groupName)-Callback for VehicleGroupSpawned event
M.onVehicleMapmgrUpdate(id)-Callback for VehicleMapmgrUpdate event
M.onVehicleResetted(id)-Callback for VehicleResetted event
M.onVehicleSpawned(id)-Callback for VehicleSpawned event
M.onVehicleSwitched(oldId, newId)-Callback for VehicleSwitched event
M.refreshVehicles()-refreshVehicles handler
M.removeTraffic(id, stopAi)-removeTraffic handler
M.scatterTraffic(vehIds, minDist, maxDist)-scatterTraffic handler
M.setActiveAmount(amount)-Sets ActiveAmount
M.setDebugMode(value)-Sets DebugMode
M.setFocus(mode, data)-Sets Focus
M.setTrafficVars(data, reset)-Sets TrafficVars
M.setupCustomTraffic(amount, params)-Sets upCustomTraffic
M.setupTraffic(amount, policeRatio, options)-Sets upTraffic
M.setupTrafficWaitForUi(usePolice)-Sets upTrafficWaitForUi
M.showMessagesvalue-if enabled, UI messages can be automatically shown
M.spawnTraffic(amount, groupData, options)-public interface
M.toggle(keepInMemory)-keepInMemory allows instantenous reactivation at the expense of RAM consumption when traffic is disabled
M.trackAIAllVeh(mode)-trackAIAllVeh handler
M.unfreezeState(trafficData, policeData, parkingData)-unfreezeState handler

Internals

Traffic Variables (vars)

{
  spawnValue = 1,         -- respawn frequency (0 = disabled, 3 = rapid)
  spawnDirBias = 0.2,     -- direction bias (-1 away, 1 towards player)
  activeAmount = huge,    -- max active vehicles
  baseAggression = 0.35,  -- AI aggression
  speedLimit = -1,        -- global speed limit override (-1 = use road limits)
  aiMode = "traffic",     -- default AI mode
  aiAware = "auto",       -- car avoidance mode
  aiDebug = "off",        -- debug rendering
  enableRandomEvents = false
}

Vehicle Pooling

Traffic uses core_vehicleActivePooling to manage a pool of active/inactive vehicles. When the active count exceeds activeAmount, vehicles are deactivated (mesh hidden, physics stopped). Deactivated vehicles get _teleport flag and are repositioned when reactivated.

Spawning Theory

Vehicles respawn along a route ahead of the focus point. The system considers:

  • Road density: Branch node count in 200m radius affects spawn distance
  • Drivability: Roads below threshold are skipped; narrow roads get reduced drivability
  • Direction scattering: Adjusts bias based on ratio of outbound vs inbound traffic
  • Dynamic sampling: Every 5 seconds, samples local conditions to tune spawn parameters

Focus System

The focus point determines where traffic is centered:

  • "camera" (default): Game camera position and forward
  • "vehicle": Player vehicle position and velocity vector
  • "custom": Arbitrary position/direction
  • Auto mode switches between camera and vehicle based on context

How It Works

  1. setupTraffic() creates vehicle groups (optionally with police), calls spawnTraffic()
  2. onVehicleGroupSpawned → activate() inserts vehicles into traffic table
  3. onTrafficStarted initializes the pool, focus, and variables
  4. onUpdate runs the main loop: updates focus, processes vehicle pool, calls doTraffic()
  5. doTraffic iterates all vehicles, calling their onUpdate and processing one respawn per frame
  6. When a vehicle goes out of range, it fades out and re-queues for respawn ahead

Usage Example

-- Start traffic with 10 vehicles, 25% police
gameplay_traffic.setupTraffic(10, 0.25)

-- Adjust traffic speed limit
gameplay_traffic.setTrafficVars({speedLimit = 13.89}) -- 50 km/h

-- Get all traffic data
local data = gameplay_traffic.getTrafficData()
for id, veh in pairs(data) do
  log("I", "", string.format("Vehicle %d: %s at %0.1f m/s", id, veh.modelName, veh.speed))
end

-- Toggle traffic off/on
gameplay_traffic.toggle()

See Also

  • Gameplay Achievement - Related reference
  • Gameplay City - Related reference
  • discover - Discover / Experience System - Related reference
  • Gameplay Systems Guide - Guide

Taxi Ride System

Reference for `gameplay_taxi`, which manages the full taxi ride experience - finding nearby taxis, hailing, entering, choosing a destination via the big map, AI-driven travel, idle camera, skip/telepo

Vehicle Performance

Reference for `gameplay_vehiclePerformance`, which calculates a Performance Index (PI) from drag test data and assigns vehicles to performance classes (D through X).

On this page

Module Exports (M)Setup & LifecycleVehicle ManagementFocus & TeleportingState & ConfigQueriesAliasesHooks / LifecycleModule FieldsInternalsTraffic Variables (vars)Vehicle PoolingSpawning TheoryFocus SystemHow It WorksUsage ExampleSee Also