How to Spawn and Control a Car in CARLA Environment

In the last tutorial, we went through the project requirements and environment setup. We also tested the script and ensured it worked.
In this tutorial, you will learn about the Python API side of CARLA. We will work on the Python code necessary to control the car.
We will achieve this in steps, first, we will spawn a car in the environment, and then, control the car in the environment.
To begin with, you should know that there are several types of objects in Carla.
First, there is the "world," which is also the driving environment.
Then, you have the actors within this world. Actors are things like your car, the sensors on your car, pedestrians, other cars, and so on.
Finally, we have blueprints. The blueprints are the attributes of our actors.
With this in mind, let's start writing some actual code. Our first milestone will be to make a car that spawns in the environment and simply drives forward.
How to Create and Spawn a Car in CARLA Environment
We will be working on the example directory, which is where we will be writing and running our codes on the command-line.
To follow along, navigate to the example directory on your command-line and create a new file with the name autonomous-car-tutorial.py
. This is where you will be writing your codes.
- Python Code
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
All the python code above does is to find the CARLA egg file i.e the file we are using for the CARLA package itself.
The first three lines of codes simply import some important packages (glob, os and sys) necessary for running the project.
The next line of codes uses the try
and except
to ensure we import CARLA before the program runs.
To successfully import CARLA, we need to first find it.
This is why we are using the try
and except
code to find our file for now in the examples directory.
An alternative to this is to move the required CARLA files to your site-packages of Python and import it directly.
Next, we will import more packages.
- Python Code
import random
import time
import numpy as np
In the code above, we imported the random
and time
package, which are fairly common in python, while the last package imported, numpy
, was installed in the previous tutorial.
Next, we have to create a list of actors and clean-up afterward.
If you can recall from the previous tutorial, our autonomous self-driving car project has both a client (the Python API) and server (CARLA simulator).
When we start running a client on the server, we create actors on the server. If we exit the program without cleaning up, our actors will still be on the server.
- Python Code
actor_list = []
try:
finally:
print('Cleaning up actors...')
for actor in actor_list:
actor.destroy()
print('Done, Actors cleaned-up successfully!')
In the code above, we created an empty list
of actors.
In the next lines, we placed the main block of codes in a try
and finally
function.
Even though the try
block is currently empty, this is where we will put all our logic and actor creation, and then, the finally
cleans up the program. When it runs, it displays "Cleaning up actors..."; thereafter, it loops through all list
of actors and destroys them, when completed it displays "Done, Actors cleaned-up successfully!"
Next, we will fill in the try block.
- Python Code
actor_list = []
try:
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
world = client.get_world()
blueprint_library = world.get_blueprint_library()
In the code above, we created a client
variable and assigned it to the Client
class with two parameters, the localhost and port number: 2000.
The client is the program itself.
The next line sets a time of 2 seconds on the client.
Next, we created a world actor by calling the get_world()
method on the client
variable and storing it as world
.
Afterward, we created a blueprint to work with by calling the get_blueprint_library()
method on the world
variable and storing it as blueprint_library
.
The get_world()
and get_blueprint_library()
methods comes preinstalled with CARLA.
Note that you need to have carla running (the shell or .exe) to connect.
- Sikademy Tips
Now that we have created the blueprints, we can filter for an actor. For instance:
tesla_model3 = blueprint_library.filter('model3')[0]
The code above will give us the default blueprint for the Tesla Model 3.
Now that we have the blueprint for Tesla Model 3, we can spawn this vehicle in the environment, but we don't have a location in mind.
CARLA is prebuilt with about 200 spawn points, which we can just pick randomly if we do not have a particular spawn point in mind.
The code below will create a spawn point by randomly choosing from the list of spawn points.
spawn_point = random.choice(world.get_map().get_spawn_points())
Now that we have a spawn point and a car, we can go ahead and spawn the car into the world using the code below.
vehicle = world.spawn_actor(tesla_model3, spawn_point)
We can also control the car with throttling and steering with the code below:
control_vehicle = carla.VehicleControl(throttle=1.0, steer=0.0)
vehicle.apply_control(control_vehicle)
The code above assigns the desired controls to a variable named control_vehicle
, and uses the apply_control()
method in CARLA to call the controls on the vehicle
that was created.
Finally, let's add this vehicle to our list of actors that we need to track and clean up. To do that, use the code below:
actor_list.append(vehicle)
The code above adds the vehicle as an item to the empty actor_list
we created earlier.
Now that we have a car with controls added to the list of actors, we can work with this. Let's just run the program for 10 seconds and then clean up:
time.sleep(10)
With this, we can compile the complete code we have so far:
- Python Code
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
import random
import time
import numpy as np
actor_list = []
try:
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
world = client.get_world()
blueprint_library = world.get_blueprint_library()
tesla_model3 = blueprint_library.filter('model3')[0]
print(tesla_model3)
spawn_point = random.choice(world.get_map().get_spawn_points())
vehicle = world.spawn_actor(tesla_model3, spawn_point)
control_vehicle = carla.VehicleControl(throttle=1.0, steer=0.0)
vehicle.apply_control(control_vehicle)
actor_list.append(vehicle)
# sleep for 10 seconds, then finish:
time.sleep(10)
finally:
print('Cleaning up actors...')
for actor in actor_list:
actor.destroy()
print('Done, Actors cleaned-up successfully!')
We can run the program we have so far.
If you find it difficult to locate the car you created in the given 10 seconds, go to the part of the server that displays the CARLA environment, use your mouse to look down, and then tap "s" on your keyboard to start zooming away.
That should give you a complete overhead look over the entire environment while looking from above.
In our demo, we can see it driving, we marked it with a red circle in the screenshot below:
It is kind of hard to spot our autonomous self-driving car at first glance, but when it's in motion, it becomes easy to see.
Take note, since we are using a random location each time we run the program, the car may not spawn in the same place as last spotted and could spawn in a tunnel. If there happens to be a situation where you don't see your vehicle, just run the program again.
- Sikademy Tips
So far, so good, everything works as it should.
In the next tutorial, we will work on the camera sensor of our autonomous self-driving car, and figure out how to access the data from it.
Wrap Off
If you completed this tutorial up to this point, you are ready to proceed to the next tutorial.
In the next tutorial, we will use the codes from this tutorial to add an RGB forward-facing camera to the hood of our autonomous self-driving car.
If you run into errors or unable to complete this tutorial, feel free to contact us anytime, and we will instantly resolve it. You can also request clarification, download this tutorial as a pdf or report bugs using the buttons below.