| 678 | |
| 679 | |
| 680 | class CollisionSensor(object): |
| 681 | def __init__(self, parent_actor, hud): |
| 682 | self.sensor = None |
| 683 | self.history = [] |
| 684 | self._parent = parent_actor |
| 685 | self.hud = hud |
| 686 | world = self._parent.get_world() |
| 687 | bp = world.get_blueprint_library().find('sensor.other.collision') |
| 688 | self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent) |
| 689 | # We need to pass the lambda a weak reference to self to avoid circular |
| 690 | # reference. |
| 691 | weak_self = weakref.ref(self) |
| 692 | self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event)) |
| 693 | |
| 694 | def get_collision_history(self): |
| 695 | history = collections.defaultdict(int) |
| 696 | for frame, intensity in self.history: |
| 697 | history[frame] += intensity |
| 698 | return history |
| 699 | |
| 700 | @staticmethod |
| 701 | def _on_collision(weak_self, event): |
| 702 | self = weak_self() |
| 703 | if not self: |
| 704 | return |
| 705 | actor_type = get_actor_display_name(event.other_actor) |
| 706 | self.hud.notification('Collision with %r' % actor_type) |
| 707 | impulse = event.normal_impulse |
| 708 | intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2) |
| 709 | self.history.append((event.frame, intensity)) |
| 710 | if len(self.history) > 4000: |
| 711 | self.history.pop(0) |
| 712 | |
| 713 | |
| 714 | # ============================================================================== |