| 624 | |
| 625 | |
| 626 | class CollisionSensor(object): |
| 627 | def __init__(self, parent_actor, hud): |
| 628 | self.sensor = None |
| 629 | self.history = [] |
| 630 | self._parent = parent_actor |
| 631 | self.hud = hud |
| 632 | world = self._parent.get_world() |
| 633 | bp = world.get_blueprint_library().find('sensor.other.collision') |
| 634 | self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) |
| 635 | # We need to pass the lambda a weak reference to self to avoid circular |
| 636 | # reference. |
| 637 | weak_self = weakref.ref(self) |
| 638 | self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event)) |
| 639 | |
| 640 | def get_collision_history(self): |
| 641 | history = collections.defaultdict(int) |
| 642 | for frame, intensity in self.history: |
| 643 | history[frame] += intensity |
| 644 | return history |
| 645 | |
| 646 | @staticmethod |
| 647 | def _on_collision(weak_self, event): |
| 648 | self = weak_self() |
| 649 | if not self: |
| 650 | return |
| 651 | actor_type = get_actor_display_name(event.other_actor) |
| 652 | self.hud.notification('Collision with %r' % actor_type) |
| 653 | impulse = event.normal_impulse |
| 654 | intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2) |
| 655 | self.history.append((event.frame, intensity)) |
| 656 | if len(self.history) > 4000: |
| 657 | self.history.pop(0) |
| 658 | |
| 659 | |
| 660 | # ============================================================================== |