Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:CARLA simulator Carla BasicAgent Vehicle Obstacle Detected

From Leeroopedia
Knowledge Sources
Domains Computational Geometry, Obstacle Detection, Autonomous Driving
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for detecting vehicle and walker obstacles along the planned route provided by the CARLA simulator agents library. The _vehicle_obstacle_detected() method constructs a geometric corridor from upcoming waypoints and checks whether any actor's bounding box intersects it, returning the closest blocking actor and its distance.

Description

This method is the core perception routine called by BasicAgent.run_step() at each simulation tick. It:

  1. Retrieves the ego vehicle's current transform and the upcoming waypoints from the local planner
  2. Constructs a route corridor as a Shapely polygon from the waypoint sequence, using lane width to define corridor boundaries
  3. Iterates over the provided vehicle/walker list (or fetches all vehicles/walkers from the world if not provided)
  4. For each candidate actor within max_distance:
    • Projects its bounding box vertices onto the 2D ground plane
    • Checks if the vertical angle to the actor falls within [low_angle_th, up_angle_th]
    • Tests whether the actor's 2D footprint polygon intersects the route corridor
  5. Returns a tuple indicating whether an obstacle was detected, the blocking actor reference, and the distance to it

The method supports a lane_offset parameter that shifts the corridor laterally, enabling adjacent-lane obstacle checks for lane-change safety evaluation.

Usage

Use this method when you need to determine if there are blocking actors on the ego vehicle's planned path. It is called internally by BasicAgent.run_step() for both vehicle and walker detection, and by BehaviorAgent for lane-change feasibility assessment.

Code Reference

Source Location

  • Repository: CARLA
  • File: PythonAPI/carla/agents/navigation/basic_agent.py
  • Lines: L315-419

Signature

def _vehicle_obstacle_detected(self, vehicle_list=None, max_distance=None,
                                up_angle_th=90, low_angle_th=0, lane_offset=0):
    """
    Method to check if there is a vehicle or walker blocking ahead
    of the agent in the route corridor.

    :param vehicle_list: list of actors to check (if None, queries world)
    :param max_distance: max detection range in meters
    :param up_angle_th: upper vertical angle threshold in degrees
    :param low_angle_th: lower vertical angle threshold in degrees
    :param lane_offset: lateral offset in number of lanes (0=current, 1=right, -1=left)
    :return: (bool, carla.Actor or None, float)
    """

Import

from agents.navigation.basic_agent import BasicAgent
# Method accessed as agent._vehicle_obstacle_detected(...)

I/O Contract

Inputs

Name Type Required Description
vehicle_list list[carla.Actor] No (default: None) Pre-filtered list of actors to check. If None, the method queries world.get_actors().filter('vehicle.*') or 'walker.*'.
max_distance float No (default: None) Maximum detection range in meters. If None, uses the agent's _base_vehicle_threshold (default 5 m) scaled by the ego vehicle's current speed.
up_angle_th float No (default: 90) Upper vertical angle threshold in degrees. Actors above this angle relative to the ego vehicle are ignored.
low_angle_th float No (default: 0) Lower vertical angle threshold in degrees. Actors below this angle are ignored.
lane_offset int No (default: 0) Lateral lane offset for corridor construction. 0 = current lane, positive = right, negative = left.

Outputs

Name Type Description
(detected, actor, distance) tuple[bool, carla.Actor or None, float] A 3-tuple: detected is True if an obstacle was found; actor is the closest blocking actor (or None); distance is the Euclidean distance to the obstacle in meters.

Usage Examples

Basic Example

import carla
from agents.navigation.basic_agent import BasicAgent

client = carla.Client('localhost', 2000)
world = client.get_world()

# Spawn ego vehicle
bp = world.get_blueprint_library().find('vehicle.tesla.model3')
spawn_point = world.get_map().get_spawn_points()[0]
vehicle = world.spawn_actor(bp, spawn_point)

agent = BasicAgent(vehicle, target_speed=30)
agent.set_destination(world.get_map().get_spawn_points()[50].location)

# Manual obstacle check in the driving loop
while not agent.done():
    # Check for vehicle obstacles
    vehicle_list = world.get_actors().filter('vehicle.*')
    detected, blocking_actor, distance = agent._vehicle_obstacle_detected(
        vehicle_list=vehicle_list,
        max_distance=20.0
    )

    if detected:
        print(f"Obstacle detected: {blocking_actor.type_id} at {distance:.1f}m")
        # Apply emergency brake
        control = carla.VehicleControl()
        control.brake = 1.0
        vehicle.apply_control(control)
    else:
        control = agent.run_step()
        vehicle.apply_control(control)

    world.tick()

Lane Change Safety Check

# Check if the left lane is clear before changing
detected_left, _, dist_left = agent._vehicle_obstacle_detected(
    vehicle_list=vehicle_list,
    max_distance=15.0,
    lane_offset=-1  # Check the left adjacent lane
)

detected_right, _, dist_right = agent._vehicle_obstacle_detected(
    vehicle_list=vehicle_list,
    max_distance=15.0,
    lane_offset=1  # Check the right adjacent lane
)

if not detected_left:
    print("Left lane clear for lane change")
elif not detected_right:
    print("Right lane clear for lane change")
else:
    print("Both adjacent lanes blocked, staying in current lane")

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment