| 574 | |
| 575 | |
| 576 | class CollisionSensor(object): |
| 577 | def __init__(self, parent_actor, hud): |
| 578 | self.sensor = None |
| 579 | self.history = [] |
| 580 | self._parent = parent_actor |
| 581 | self.hud = hud |
| 582 | world = self._parent.get_world() |
| 583 | bp = world.get_blueprint_library().find('sensor.other.collision') |
| 584 | self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) |
| 585 | # We need to pass the lambda a weak reference to self to avoid circular |
| 586 | # reference. |
| 587 | weak_self = weakref.ref(self) |
| 588 | self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event)) |
| 589 | |
| 590 | def get_collision_history(self): |
| 591 | history = collections.defaultdict(int) |
| 592 | for frame, intensity in self.history: |
| 593 | history[frame] += intensity |
| 594 | return history |
| 595 | |
| 596 | @staticmethod |
| 597 | def _on_collision(weak_self, event): |
| 598 | self = weak_self() |
| 599 | if not self: |
| 600 | return |
| 601 | actor_type = get_actor_display_name(event.other_actor) |
| 602 | self.hud.notification('Collision with %r' % actor_type) |
| 603 | impulse = event.normal_impulse |
| 604 | intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2) |
| 605 | self.history.append((event.frame, intensity)) |
| 606 | if len(self.history) > 4000: |
| 607 | self.history.pop(0) |
| 608 | |
| 609 | |
| 610 | # ============================================================================== |