Keyboard control for the human agent
| 165 | |
| 166 | |
| 167 | class KeyboardControl(object): |
| 168 | |
| 169 | """ |
| 170 | Keyboard control for the human agent |
| 171 | """ |
| 172 | |
| 173 | def __init__(self): |
| 174 | """ |
| 175 | Init |
| 176 | """ |
| 177 | self._control = carla.VehicleControl() |
| 178 | self._steer_cache = 0.0 |
| 179 | |
| 180 | def parse_events(self, control, clock): |
| 181 | """ |
| 182 | Parse the keyboard events and set the vehicle controls accordingly |
| 183 | """ |
| 184 | for event in pygame.event.get(): |
| 185 | if event.type == pygame.QUIT: |
| 186 | return |
| 187 | |
| 188 | self._parse_vehicle_keys(pygame.key.get_pressed(), clock.get_time()) |
| 189 | control.steer = self._control.steer |
| 190 | control.throttle = self._control.throttle |
| 191 | control.brake = self._control.brake |
| 192 | control.hand_brake = self._control.hand_brake |
| 193 | |
| 194 | def _parse_vehicle_keys(self, keys, milliseconds): |
| 195 | """ |
| 196 | Calculate new vehicle controls based on input keys |
| 197 | """ |
| 198 | self._control.throttle = 0.6 if keys[K_UP] or keys[K_w] else 0.0 |
| 199 | steer_increment = 15.0 * 5e-4 * milliseconds |
| 200 | if keys[K_LEFT] or keys[K_a]: |
| 201 | self._steer_cache -= steer_increment |
| 202 | elif keys[K_RIGHT] or keys[K_d]: |
| 203 | self._steer_cache += steer_increment |
| 204 | else: |
| 205 | self._steer_cache = 0.0 |
| 206 | |
| 207 | self._steer_cache = min(0.95, max(-0.95, self._steer_cache)) |
| 208 | self._control.steer = round(self._steer_cache, 1) |
| 209 | self._control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0 |
| 210 | self._control.hand_brake = keys[K_SPACE] |