一、Ego_vehicle
通过blueprint获取所需的vehicle,在地图上获取随即生成点生成,并将其设置为自动驾驶模式。
import carla
import random
import pygame
import numpy as np
client = carla.Client('localhost', 2000)
world = client.get_world()
blueprint_library = world.get_blueprint_library()
vehicle_bp = = blueprint_library.filter('*vehicle*')
spawn_points = world.get_map().get_spawn_points()
ego_vehicle = world.spawn_actor(random.choice(vehicle_bp), random.choice(spawn_points))
ego_vehicle.set_autopilot(True)
二、Spectator Camera
- 获取camera蓝图
- 生成camera并绑定ego_vehicle
- 设置camera监听模式
camera_trans =carla.Transform(carla.Location(x=-5,z=3),carla.Rotation(pitch=-20))
camera_bp = world.get_blueprint_library().find('sensor.camera.rgb')
camera = world.spawn_actor(camera_bp, camera_trans, attach_to=ego_vehicle)
camera.listen(lambda image : pygame_callback(image,renderObject))
三、设置Pygame
class RenderObject(object):
def __init__(self,width, height):
init_img = np.random.randint(0,255,(height,width,3), dtype='uint8')
self.surface = pygame.surfarray.make_surface(init_img.swapaxes(0,1))
def pygame_callback(data, obj):
img = np.reshape(np.copy(data.raw_data),(data.height, data.width, 4))
img = img[:, :, :3]
img = img[:, :, ::-1]
obj.surface = pygame.surfarray.make_surface(img.swapaxes(0,1))
image_w = camera_bp.get_attribute("image_size_x").as_int()
image_h = camera_bp.get_attribute("image_size_y").as_int()
renderObject = RenderObject(image_w, image_h)
pygame.init()
gameDisplay = pygame.display.set_mode((image_w,image_h),pygame.HWSURFACE | pygame.DOUBLEBUF)
gameDisplay.fill((0, 0, 0))
gameDisplay.blit(renderObject.surface, (0,0))
pygame.display.flip()
# Game loop
crashed = False
while not crashed:
# Advance the simulation time
world.tick()
# Update the display
gameDisplay.blit(renderObject.surface, (0,0))
pygame.display.flip()
# Process the current control state
# controlObject.process_control()
# Collect key press events
for event in pygame.event.get():
# If the window is closed, break the while loop
if event.type == pygame.QUIT:
crashed = True
# Parse effect of key press event on control state
# controlObject.parse_control(event)
if event.type == pygame.KEYUP:
# TAB key switches vehicle
if event.key == pygame.K_TAB:
ego_vehicle.set_autopilot(True)
ego_vehicle = random.choice(vehicles)
# Ensure vehicle is still alive (might have been destroyed)
if ego_vehicle.is_alive:
# Stop and remove the camera
camera.stop()
camera.destroy()
# Spawn new camera and attach to new vehicle
# controlObject = ControlObject(ego_vehicle)
camera = world.spawn_actor(camera_bp, camera_init_trans, attach_to=ego_vehicle)
camera.listen(lambda image: pygame_callback(image, renderObject))
# Update PyGame window
gameDisplay.fill((0,0,0))
gameDisplay.blit(renderObject.surface, (0,0))
pygame.display.flip()
# Stop camera and quit PyGame after exiting game loop
camera.stop()
pygame.quit()