%% Spawn and Despawn Vehicles in Scenario During Simulation
% Create a driving scenario. Set the stop time for the scenario to 3 seconds.

scenario = drivingScenario('StopTime',3);

% Add a two-lane road to the scenario.

roadCenters = [0 1 0; 53 1 0];
laneSpecification = lanespec([1 1]);
road(scenario,roadCenters,'Lanes',laneSpecification);

% Add another road that intersects the first road at a right angle to form a T-shape.

roadCenters = [20.3 38.4 0; 20 3 0];
laneSpecification = lanespec(2);
road(scenario,roadCenters,'Lanes',laneSpecification)

% Add the ego vehicle to the scenario and define its waypoints. Set the ego vehicle speed to 20 m/s and generate the trajectories for the ego vehicle.

egoVehicle = vehicle(scenario,'ClassID',1, ...
                    'Position',[1.5 2.5 0]);
waypoints = [2 3 0; 13 3 0;
            21 3 0; 31 3 0;
            43 3 0; 47 3 0];
speed = 20;
smoothTrajectory(egoVehicle,waypoints,speed)

% Add a non-ego vehicle to the scenario. Set the non-ego vehicle to spawn and despawn two times during the simulation by specifying vectors for entry time and exit time. Notice that each entry time value is less than the corresponding exit time value.

nonEgovehicle1 = vehicle(scenario,'ClassID',1, ...
                'Position',[22 30 0],'EntryTime',[0.2 1.4],'ExitTime',[1.0 2.0]);

% Define the waypoints for the non-ego vehicle. Set the non-ego vehicle speed to 30 m/s and generate its trajectories.

waypoints = [22 35 0; 22 23 0;
            22 13 0; 22 7 0;
            18 -0.3 0; 12 -0.8 0; 5 -0.8 0];
speed = 30;
smoothTrajectory(nonEgovehicle1,waypoints,speed)

% Add another non-ego vehicle to the scenario. Set the second non-ego vehicle to spawn once during the simulation by specifying an entry time as a positive scalar. Since you do not specify an exit time, this vehicle will remain in the scenario until the scenario ends.

nonEgovehicle2 = vehicle(scenario,'ClassID',1, ...
                'Position',[48 -1 0],'EntryTime',2);

% Define the waypoints for the second non-ego vehicle. Set the vehicle speed to 50 m/s and generate its trajectories.

waypoints = [48 -1 0; 42 -1 0; 28 -1 0;
            16 -1 0; 12 -1 0];
speed = 50;
smoothTrajectory(nonEgovehicle2,waypoints,speed)

% Create a custom figure window to plot the scenario.

fig = figure;
set(fig,'Position',[0 0 600 600])
movegui(fig,'center')
hViewPnl = uipanel(fig,'Position',[0 0 1 1],'Title','Vehicle Spawn and Despawn');
hPlt = axes(hViewPnl);

% Plot the scenario and run the simulation. Observe how the non-ego vehicles spawn and despawn in the scenario while simulation is running.

plot(scenario,'Waypoints','on','Parent',hPlt)
while advance(scenario)
    pause(0.1)
end

% Copyright 2020 The MathWorks, Inc.