AI Vehicles

Table of Contents

RCCP includes a waypoint-based AI driving system built on Unity's NavMesh pathfinding. AI vehicles follow predefined waypoint paths, avoid obstacles dynamically, and respect brake zones for speed reduction at corners and intersections. The system supports four distinct behavior modes and requires no player input to operate.

Prerequisites: Before setting up AI vehicles, you should have a working vehicle with all core components as described in Vehicle Setup. You also need a baked NavMesh in your scene (Window > AI > Navigation).

How the AI System Works

The AI system uses three main components working together:

ComponentPurposeLocation
RCCP_AIMain AI driver that computes steering, throttle, and brakingAttached to the vehicle
RCCP_AIWaypointsContainerHolds the ordered list of waypoints that define a driving pathScene object
RCCP_AIBrakeZoneTrigger volume that tells AI vehicles to slow to a target speedScene object

The AI driver relies on a NavMeshAgent for pathfinding. When the RCCP_AI component is added or enabled, it automatically creates a child NavMeshAgent if one does not already exist. The agent does not move the vehicle directly. Instead, it calculates a path that the AI uses to compute steering and speed inputs.

Every FixedUpdate, the AI:

  1. Updates its NavMesh destination based on the current behavior mode
  2. Computes steering using a look-ahead point along the path
  3. Calculates a safe cornering speed from the tightest turn radius ahead
  4. Applies PID speed control for smooth throttle and braking
  5. Checks for stuck conditions and recovers automatically
  6. Applies obstacle avoidance adjustments from RCCP_AIDynamicObstacleAvoidance

Behavior Modes

The RCCP_AI component supports four behavior modes, set via the behaviour field in the Inspector:

ModeDescription
FollowWaypointsLoops through waypoints at moderate speed. Good for traffic or patrol vehicles.
RaceWaypointsRaces through waypoints more aggressively with an extended look-ahead distance for smoother cornering at speed.
FollowTargetFollows a target Transform at a set distance. Stops when within range. Requires the target field to be assigned.
ChaseTargetChases and intercepts a target using velocity prediction. More aggressive than FollowTarget. Requires the target field to be assigned.

Setting Up an AI Vehicle

Step 1: Prepare the Vehicle

Start with a fully configured RCCP vehicle that has RCCP_CarController and all required drivetrain components (engine, gearbox, differential, axles, wheel colliders). See Vehicle Setup for details.

Step 2: Add RCCP_OtherAddons

If the vehicle does not already have the RCCP_OtherAddons component, add it. The AI component is managed through this addons system. You can add it via:

Step 3: Add RCCP_AI

Add the AI component to the vehicle:

When the component is added, it automatically creates a child NavMeshAgent GameObject. When the AI enables at runtime, it sets CarController.externalControl = true, which overrides player input so the AI has full control of the vehicle.

Step 4: Bake a NavMesh

The AI uses Unity's NavMesh for pathfinding. Open Window > AI > Navigation and bake a NavMesh for your scene. Make sure the NavMesh covers the roads and areas where AI vehicles will drive.

Step 5: Assign a Waypoint Container

Drag a RCCP_AIWaypointsContainer from your scene into the waypointsContainer field on the RCCP_AI component. If you do not assign one, the AI will attempt to find one in the scene automatically at runtime.

Key Properties

Driving Settings

PropertyTypeDefaultDescription
behaviourBehaviourTypeRaceWaypointsAI behavior mode (see table above)
waypointsContainerRCCP_AIWaypointsContainernullReference to the waypoint path
targetTransformnullTarget for FollowTarget and ChaseTarget modes
maxThrottlefloat (0-1)1.0Maximum throttle input
maxBrakefloat (0-1)1.0Maximum brake input
agressivenessfloat (0-3)2.0Driving aggressiveness factor; higher values allow later braking
steerSensitivityfloat (0-5)3.0Steering sensitivity multiplier
roadGripfloat1.1Friction coefficient used to calculate safe cornering speed

Waypoint Settings

PropertyTypeDefaultDescription
waypointReachThresholdfloat25Distance in meters at which a waypoint is considered reached
raceLookAheadfloat36Additional look-ahead distance in meters for RaceWaypoints mode

Steering Look-ahead

PropertyTypeDefaultDescription
minLookAheadfloat5Minimum look-ahead distance in meters when stationary
lookAheadPerKphfloat0.25Additional look-ahead meters per km/h of current speed

PID Speed Control

PropertyTypeDefaultDescription
kpfloat0.2Proportional gain for speed control
kifloat0.01Integral gain for speed control
kdfloat0.02Derivative gain for speed control

Target Following

PropertyTypeDefaultDescription
followTargetDistancefloat5Distance to maintain behind target in FollowTarget mode
chasePredictionTimefloat1Prediction time in seconds for intercepting targets in ChaseTarget mode

State

PropertyTypeDefaultDescription
stopNowboolfalseForces the AI to stop immediately
reverseNowboolfalseForces the AI to reverse
checkStuckbooltrueEnables stuck detection and automatic recovery

Waypoint System

RCCP_AIWaypointsContainer

This component holds an ordered list of RCCP_Waypoint child objects that define the AI driving path. The AI follows waypoints sequentially and loops back to the first waypoint after reaching the last one.

Creating a waypoint container:

Use the menu: Tools > BoneCracker Games > Realistic Car Controller Pro > Create > Scene > Add AI Waypoints Container

This creates a new GameObject with the RCCP_AIWaypointsContainer component.

RCCP_Waypoint

Each waypoint is a child GameObject of the container with the RCCP_Waypoint component. Waypoints define the positions the AI will drive through. Position them along the road where you want the AI to drive.

Waypoint Container Properties

PropertyTypeDefaultDescription
smoothingSubdivisionsint5Number of subdivisions per segment when smoothing the path
groundOffsetfloat1.0Height above ground to place each waypoint during ground snapping
groundLayerMaskLayerMaskEverythingLayers to include when raycasting for ground

Waypoint Container Context Menu Tools

Right-click the RCCP_AIWaypointsContainer component in the Inspector to access these tools:

Tips for Good Waypoint Placement

Brake Zones

RCCP_AIBrakeZone

A brake zone is a trigger volume that tells AI vehicles to reduce speed. When an AI vehicle enters a brake zone, it limits its target speed to the zone's targetSpeed value. When the vehicle exits, normal speed calculation resumes.

PropertyTypeRangeDefaultDescription
targetSpeedfloat5 - 36050Target speed in km/h that AI vehicles should not exceed inside this zone

Creating brake zones:

Use the menu: Tools > BoneCracker Games > Realistic Car Controller Pro > Create > Scene > Add AI Brake Zones Container

This creates a RCCP_AIBrakeZonesContainer with a BoxCollider (set as trigger). Each child brake zone also requires a BoxCollider marked as trigger.

RCCP_AIBrakeZonesContainer

This is a parent container that holds multiple RCCP_AIBrakeZone children. It draws red gizmos in the Scene view to visualize each brake zone's bounds. At runtime it automatically sets brake zone GameObjects to the "Ignore Raycast" layer.

Placing Brake Zones

Obstacle Avoidance

RCCP_AIDynamicObstacleAvoidance

This optional component provides dynamic obstacle detection and avoidance. It works alongside RCCP_AI by contributing additional steering input when obstacles are detected.

How it works:

  1. Detects obstacles within a configurable radius using Physics.OverlapSphere
  2. Samples obstacle bounds with raycasts to find actual threat points
  3. Assesses collision risk using trajectory prediction
  4. Calculates a safe avoidance direction (left or right) based on clearance
  5. Applies steering and braking inputs proportional to threat urgency

Key properties:

PropertyTypeDefaultDescription
autoDetectObstaclesbooltrueAutomatically detect obstacles from scene colliders
dynamicObstacleLayersLayerMask--Layers considered for automatic detection
detectionRadiusfloat10Maximum detection radius in meters
predictionTimefloat1Seconds to look ahead when predicting positions
riskThresholdfloat0.3Minimum risk level (0-1) to trigger avoidance
vehicleWidthfloat2Vehicle width for collision prediction
vehicleLengthfloat4Vehicle length for collision prediction
safetyMarginfloat0.5Safety margin added to vehicle dimensions
emergencyBrakeDistancefloat2Distance at which maximum braking is applied

Adding and removing obstacles manually:


RCCP_AIDynamicObstacleAvoidance avoidance = vehicle.GetComponent<RCCP_AIDynamicObstacleAvoidance>();

// Add a specific obstacle to track
avoidance.AddObstacle(obstacleTransform);

// Remove an obstacle from tracking
avoidance.RemoveObstacle(obstacleTransform);

Spawning AI Vehicles from Code

Use the RCCP.SpawnRCC static method to instantiate AI vehicles at runtime. For AI vehicles, set registerAsPlayerVehicle to false and isControllable to false:


// Spawn an AI vehicle
RCCP_CarController aiVehicle = RCCP.SpawnRCC(
    aiPrefab,        // Vehicle prefab with RCCP_AI component
    spawnPos,        // World position
    spawnRot,        // World rotation
    false,           // Do not register as player vehicle
    false,           // Not controllable by player
    true             // Start with engine running
);

The vehicle must have the RCCP_AI component on the prefab. When it spawns and OnEnable runs, the AI detects the RCCP_AI component and fires RCCP_Events.OnRCCPAISpawned instead of the normal player spawn event.

Changing AI Behavior at Runtime


RCCP_AI ai = aiVehicle.OtherAddonsManager.AI;

// Switch to follow a target
ai.behaviour = RCCP_AI.BehaviourType.FollowTarget;
ai.target = playerVehicle.transform;

// Force stop
ai.stopNow = true;

// Reset the AI state
ai.Reload();

Events

The RCCP event system provides two AI-specific events:

EventSignatureFired When
RCCP_Events.OnRCCPAISpawnedonRCCPAISpawned(RCCP_CarController)An AI vehicle is enabled (has RCCP_AI component on OtherAddonsManager)
RCCP_Events.OnRCCPAIDestroyedonRCCPAIDestroyed(RCCP_CarController)An AI vehicle is disabled or destroyed

Subscribing to AI events:


void OnEnable() {
    RCCP_Events.OnRCCPAISpawned += OnAISpawned;
    RCCP_Events.OnRCCPAIDestroyed += OnAIDestroyed;
}

void OnDisable() {
    RCCP_Events.OnRCCPAISpawned -= OnAISpawned;
    RCCP_Events.OnRCCPAIDestroyed -= OnAIDestroyed;
}

void OnAISpawned(RCCP_CarController aiVehicle) {
    Debug.Log("AI vehicle spawned: " + aiVehicle.name);
}

void OnAIDestroyed(RCCP_CarController aiVehicle) {
    Debug.Log("AI vehicle destroyed: " + aiVehicle.name);
}

The distinction between player and AI spawn events is automatic. If the vehicle has an RCCP_AI component registered through OtherAddonsManager, it fires the AI events. Otherwise, it fires the standard player events. See API Reference for the full event reference.

Stuck Detection and Recovery

When checkStuck is enabled (the default), the AI monitors whether the vehicle is stuck. If the vehicle has been applying throttle but moving below 2 km/h for more than 2 seconds, it triggers a recovery routine that:

  1. Temporarily enables autoReverse on the input component
  2. Reverses for 1.5 seconds
  3. Restores normal settings and shifts back to first gear

Scene View Gizmos

When the game is playing, RCCP_AI draws helpful gizmos in the Scene view:

Brake zone containers draw semi-transparent red boxes showing each brake zone's bounds.

Common Issues

ProblemPossible CauseSolution
AI not movingNo waypoint container assignedAssign a RCCP_AIWaypointsContainer to the waypointsContainer field
AI not movingNavMesh not bakedBake a NavMesh covering the driving area (Window > AI > Navigation)
AI not movingMissing drivetrain componentsVerify the vehicle has engine, gearbox, differential, and axles
AI driving off the roadNot enough waypointsAdd more waypoints along the road, especially at curves
AI not braking at turnsNo brake zones placedAdd RCCP_AIBrakeZone triggers before sharp turns
AI jittering at waypointswaypointReachThreshold too smallIncrease the threshold so the AI transitions smoothly between waypoints
AI cutting cornersraceLookAhead too highReduce the look-ahead value or switch to FollowWaypoints mode
AI colliding with obstaclesNo obstacle avoidance componentAdd RCCP_AIDynamicObstacleAvoidance and configure its dynamicObstacleLayers
AI stuck at an obstacleStuck detection disabledEnable checkStuck on the RCCP_AI component

Related topics: Vehicle Setup | Settings | Inputs | Recording and Playback

Support: bonecrackergames@gmail.com | www.bonecrackergames.com

Need help? See Troubleshooting