avian3d/collision/
collision_events.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! Collision events for detecting when colliders start or stop touching.
//!
//! Depending on your use case, you may want to use either buffered events read
//! using an [`EventReader`] or observable events triggered for specific entities.
//! Avian provides both options using separate event types.
//!
//! Note that collision events are only sent or triggered for entities that have
//! the [`CollisionEventsEnabled`] component.
//!
//! # Buffered Events
//!
//! Avian provides two different buffered collision event types:
//!
//! - [`CollisionStarted`]
//! - [`CollisionEnded`]
//!
//! These events are sent when two colliders start or stop touching, and can be read
//! using an [`EventReader`]. This can be useful for efficiently processing large numbers
//! of collision events between pairs of entities, such as for detecting bullet hits
//! or playing impact sounds when two objects collide.
//!
//! The events are only sent if one of the entities has the [`CollisionEventsEnabled`] component.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
//! use bevy::prelude::*;
//!
//! fn print_started_collisions(mut collision_event_reader: EventReader<CollisionStarted>) {
//!     for CollisionStarted(entity1, entity2) in collision_event_reader.read() {
//!         println!("{entity1} and {entity2} started colliding");
//!     }
//! }
//! ```
//!
//! # Observable Events
//!
//! Avian provides two observable collision event types:
//!
//! - [`OnCollisionStart`]
//! - [`OnCollisionEnd`]
//!
//! These events are triggered for [observers](Observer) when two colliders start or stop touching.
//! This makes them good for entity-specific collision scenarios, such as for detecting when a player
//! steps on a pressure plate or enters a trigger volume.
//!
//! The events are only triggered if the target entity has the [`CollisionEventsEnabled`] component.
//!
//! ```
#![cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#![cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
//! use bevy::prelude::*;
//!
//! #[derive(Component)]
//! struct Player;
//!
//! #[derive(Component)]
//! struct PressurePlate;
//!
//! fn setup_pressure_plates(mut commands: Commands) {
//!     commands.spawn((
//!         PressurePlate,
#![cfg_attr(feature = "2d", doc = "        Collider::rectangle(1.0, 1.0),")]
#![cfg_attr(feature = "3d", doc = "        Collider::cuboid(1.0, 0.1, 1.0),")]
//!         Sensor,
//!         // Enable collision events for this entity.
//!         CollisionEventsEnabled,
//!     ))
//!     .observe(|trigger: Trigger<OnCollisionStart>, player_query: Query<&Player>| {
//!         let pressure_plate = trigger.target();
//!         let other_entity = trigger.collider;
//!         if player_query.contains(other_entity) {
//!             println!("Player {other_entity} stepped on pressure plate {pressure_plate}");
//!         }
//!     });
//! }
//! ```

use bevy::prelude::*;

/// A buffered [collision event](super#collision-events) that is sent when two colliders start touching.
///
/// The event is only sent if one of the entities has the [`CollisionEventsEnabled`] component.
///
/// Unlike [`OnCollisionStart`], this event is *not* triggered for observers.
/// Instead, you must use an [`EventReader`] to read the event in a system.
/// This makes it good for efficiently processing large numbers of collision events
/// between pairs of entities.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn print_started_collisions(mut collision_event_reader: EventReader<CollisionStarted>) {
///     for CollisionStarted(entity1, entity2) in collision_event_reader.read() {
///         println!("{entity1} and {entity2} started colliding");
///     }
/// }
/// ```
///
/// # Scheduling
///
/// The [`CollisionStarted`] event is sent in the [`NarrowPhaseSet::Update`] system set,
/// but can be read at any time.
///
/// [`NarrowPhaseSet::Update`]: super::narrow_phase::NarrowPhaseSet::Update
#[derive(Event, Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct CollisionStarted(pub Entity, pub Entity);

/// A buffered [collision event](super#collision-events) that is sent when two colliders stop touching.
///
/// The event is only sent if one of the entities has the [`CollisionEventsEnabled`] component.
///
/// Unlike [`OnCollisionEnd`], this event is *not* triggered for observers.
/// Instead, you must use an [`EventReader`] to read the event in a system.
/// This makes it good for efficiently processing large numbers of collision events
/// between pairs of entities.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn print_ended_collisions(mut collision_event_reader: EventReader<CollisionEnded>) {
///     for CollisionEnded(entity1, entity2) in collision_event_reader.read() {
///         println!("{entity1} and {entity2} stopped colliding");
///     }
/// }
/// ```
///
/// # Scheduling
///
/// The [`CollisionEnded`] event is sent in the [`NarrowPhaseSet::Update`] system set,
/// but can be read at any time.
///
/// Note that if one of the colliders was removed or the bounding boxes of the colliders stopped
/// overlapping, the [`ContactPair`] between the entities was also removed, and the contact data
/// will not be available through [`Collisions`].
///
/// [`NarrowPhaseSet::Update`]: super::narrow_phase::NarrowPhaseSet::Update
/// [`ContactPair`]: super::ContactPair
/// [`Collisions`]: super::Collisions
#[derive(Event, Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct CollisionEnded(pub Entity, pub Entity);

/// A [collision event](super#collision-events) that is triggered for [observers](Observer)
/// when two colliders start touching.
///
/// The event is only triggered if the target entity has the [`CollisionEventsEnabled`] component.
///
/// Unlike [`CollisionStarted`], this event can *not* be read using an [`EventReader`].
/// Instead, you must use an [observer](Observer). This makes it good for entity-specific
/// collision listeners.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// #[derive(Component)]
/// struct Player;
///
/// #[derive(Component)]
/// struct PressurePlate;
///
/// fn setup_pressure_plates(mut commands: Commands) {
///     commands.spawn((
///         PressurePlate,
#[cfg_attr(feature = "2d", doc = "        Collider::rectangle(1.0, 1.0),")]
#[cfg_attr(feature = "3d", doc = "        Collider::cuboid(1.0, 0.1, 1.0),")]
///         Sensor,
///         // Enable collision events for this entity.
///         CollisionEventsEnabled,
///     ))
///     .observe(|trigger: Trigger<OnCollisionStart>, player_query: Query<&Player>| {
///         let pressure_plate = trigger.target();
///         let other_entity = trigger.collider;
///         if player_query.contains(other_entity) {
///             println!("Player {other_entity} stepped on pressure plate {pressure_plate}");
///         }
///     });
/// }
/// ```
///
/// # Scheduling
///
/// The [`OnCollisionStart`] event is triggered after the physics step in the [`CollisionEventSystems`]
/// system set. At this point, the solver has already run and contact impulses have been updated.
///
/// [`CollisionEventSystems`]: super::narrow_phase::CollisionEventSystems
#[derive(Event, Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct OnCollisionStart {
    /// The entity of the collider that started colliding with the [`Trigger::target`].
    pub collider: Entity,
    /// The entity of the rigid body that started colliding with the [`Trigger::target`].
    ///
    /// If the collider is not attached to a rigid body, this will be `None`.
    pub body: Option<Entity>,
}

/// A [collision event](super#collision-events) that is triggered for [observers](Observer)
/// when two colliders stop touching.
///
/// The event is only triggered if the target entity has the [`CollisionEventsEnabled`] component.
///
/// Unlike [`CollisionEnded`], this event can *not* be read using an [`EventReader`].
/// Instead, you must use an [observer](Observer). This makes it good for entity-specific
/// collision listeners.
///
/// # Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// #[derive(Component)]
/// struct Player;
///
/// #[derive(Component)]
/// struct PressurePlate;
///
/// fn setup_pressure_plates(mut commands: Commands) {
///     commands.spawn((
///         PressurePlate,
#[cfg_attr(feature = "2d", doc = "        Collider::rectangle(1.0, 1.0),")]
#[cfg_attr(feature = "3d", doc = "        Collider::cuboid(1.0, 0.1, 1.0),")]
///         Sensor,
///         // Enable collision events for this entity.
///         CollisionEventsEnabled,
///     ))
///     .observe(|trigger: Trigger<OnCollisionEnd>, player_query: Query<&Player>| {
///         let pressure_plate = trigger.target();
///         let other_entity = trigger.collider;
///         if player_query.contains(other_entity) {
///             println!("Player {other_entity} stepped off of pressure plate {pressure_plate}");
///         }
///     });
/// }
/// ```
///
/// # Scheduling
///
/// The [`OnCollisionEnd`] event is triggered after the physics step in the [`CollisionEventSystems`]
/// system set. At this point, the solver has already run and contact impulses have been updated.
///
/// Note that if one of the colliders was removed or the bounding boxes of the colliders stopped
/// overlapping, the [`ContactPair`] between the entities was also removed, and the contact data
/// will not be available through [`Collisions`].
///
/// [`CollisionEventSystems`]: super::narrow_phase::CollisionEventSystems
/// [`ContactPair`]: super::ContactPair
/// [`Collisions`]: super::Collisions
#[derive(Event, Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct OnCollisionEnd {
    /// The entity of the collider that stopped colliding with the [`Trigger::target`].
    pub collider: Entity,
    /// The entity of the rigid body that stopped colliding with the [`Trigger::target`].
    ///
    /// If the collider is not attached to a rigid body, this will be `None`.
    pub body: Option<Entity>,
}

/// A marker component that enables [collision events](self) for an entity.
///
/// This enables both the buffered [`CollisionStarted`] and [`CollisionEnded`] events,
/// as well as the observable [`OnCollisionStart`] and [`OnCollisionEnd`] events.
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug)]
pub struct CollisionEventsEnabled;