avian3d/dynamics/rigid_body/mod.rs
1//! Common components and bundles for rigid bodies.
2
3pub mod forces;
4pub mod mass_properties;
5
6// Components
7mod locked_axes;
8mod physics_material;
9mod world_query;
10
11pub use forces::{ExternalAngularImpulse, ExternalForce, ExternalImpulse, ExternalTorque};
12pub use locked_axes::LockedAxes;
13pub use physics_material::{
14 CoefficientCombine, DefaultFriction, DefaultRestitution, Friction, Restitution,
15};
16pub use world_query::*;
17
18#[cfg(feature = "2d")]
19pub(crate) use forces::FloatZero;
20pub(crate) use forces::Torque;
21
22use crate::prelude::*;
23use bevy::prelude::*;
24use derive_more::From;
25
26/// A non-deformable body used for the simulation of most physics objects.
27///
28/// # Rigid Body Types
29///
30/// A rigid body can be either dynamic, kinematic or static.
31///
32/// - **Dynamic bodies** are similar to real life objects and are affected by forces and contacts.
33/// - **Kinematic bodies** can only be moved programmatically, which is useful for things like character controllers and moving platforms.
34/// - **Static bodies** can not move, so they can be good for objects in the environment like the ground and walls.
35///
36/// # Creation
37///
38/// Creating a rigid body is as simple as adding the [`RigidBody`] component,
39/// and an optional [`Collider`]:
40///
41/// ```
42#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
43#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
44/// use bevy::prelude::*;
45///
46/// fn setup(mut commands: Commands) {
47/// // Spawn a dynamic rigid body and specify its position.
48/// commands.spawn((
49/// RigidBody::Dynamic,
50/// Collider::capsule(0.5, 1.5),
51/// Transform::from_xyz(0.0, 3.0, 0.0),
52/// ));
53/// }
54/// ```
55///
56/// By default, dynamic rigid bodies will have mass properties computed based on the attached colliders
57/// and their [`ColliderDensity`]. See the [Mass properties](#mass-properties) section for more information.
58///
59/// # Movement
60///
61/// A rigid body can be moved in three ways: by modifying its position directly,
62/// by changing its velocity, or by applying forces or impulses.
63///
64/// To change the position of a rigid body, you can simply modify its `Transform`:
65///
66/// ```
67#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
68#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
69/// use bevy::prelude::*;
70///
71/// fn move_bodies(mut query: Query<&mut Transform, With<RigidBody>>) {
72/// for mut transform in &mut query {
73/// transform.translation.x += 0.1;
74/// }
75/// }
76/// ```
77///
78/// However, moving a dynamic body by changing its position directly is similar
79/// to teleporting the body, which can result in unexpected behavior since the body can move
80/// inside walls.
81///
82/// You can instead change the velocity of a dynamic or kinematic body with the [`LinearVelocity`]
83/// and [`AngularVelocity`] components:
84///
85/// ```
86#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
87#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
88/// use bevy::prelude::*;
89///
90/// # #[cfg(feature = "f32")]
91/// fn accelerate_bodies(
92/// mut query: Query<(&mut LinearVelocity, &mut AngularVelocity)>,
93/// time: Res<Time>,
94/// ) {
95/// let delta_secs = time.delta_secs();
96/// for (mut linear_velocity, mut angular_velocity) in &mut query {
97/// linear_velocity.x += 2.0 * delta_secs;
98#[cfg_attr(
99 feature = "2d",
100 doc = " angular_velocity.0 += 0.5 * delta_secs;"
101)]
102#[cfg_attr(
103 feature = "3d",
104 doc = " angular_velocity.z += 0.5 * delta_secs;"
105)]
106/// }
107/// }
108/// # #[cfg(feature = "f64")]
109/// # fn main() {}
110/// ```
111///
112/// For applying forces and impulses to dynamic bodies, see the [`ExternalForce`], [`ExternalTorque`],
113/// [`ExternalImpulse`] and [`ExternalAngularImpulse`] components.
114///
115/// Avian does not have a built-in character controller, so if you need one,
116/// you will need to implement it yourself or use a third party option.
117/// You can take a look at the [`basic_dynamic_character`] and [`basic_kinematic_character`]
118/// examples for a simple implementation.
119///
120/// [`basic_dynamic_character`]: https://github.com/Jondolf/avian/blob/42fb8b21c756a7f4dd91071597dc251245ddaa8f/crates/avian3d/examples/basic_dynamic_character.rs
121/// [`basic_kinematic_character`]: https://github.com/Jondolf/avian/blob/42fb8b21c756a7f4dd91071597dc251245ddaa8f/crates/avian3d/examples/basic_kinematic_character.rs
122///
123/// # Mass Properties
124///
125/// Every dynamic rigid body has [mass], [angular inertia], and a [center of mass].
126/// These mass properties determine how the rigid body responds to forces and torques.
127///
128/// - **Mass**: Represents resistance to linear acceleration. A higher mass requires more force for the same acceleration.
129/// - **Angular Inertia**: Represents resistance to angular acceleration. A higher angular inertia requires more torque for the same angular acceleration.
130/// - **Center of Mass**: The average position of mass in the body. Applying forces at this point produces no torque.
131///
132/// Static and kinematic rigid bodies have infinite mass and angular inertia,
133/// and do not respond to forces or torques. Zero mass for a dynamic body is also
134/// treated as a special case, and corresponds to infinite mass.
135///
136/// If no mass properties are set, they are computed automatically from attached colliders
137/// based on their shape and density.
138///
139/// ```
140#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
141#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
142/// # use bevy::prelude::*;
143/// #
144/// # fn setup(mut commands: Commands) {
145/// // Note: `ColliderDensity` is optional, and defaults to `1.0` if not present.
146/// commands.spawn((
147/// RigidBody::Dynamic,
148/// Collider::capsule(0.5, 1.5),
149/// ColliderDensity(2.0),
150/// ));
151/// # }
152/// ```
153///
154/// If mass properties are set with the [`Mass`], [`AngularInertia`], and [`CenterOfMass`] components,
155/// they override the values computed from colliders.
156///
157/// ```
158#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
159#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
160/// # use bevy::prelude::*;
161/// #
162/// # fn setup(mut commands: Commands) {
163/// // Override mass and the center of mass, but use the collider's angular inertia.
164/// commands.spawn((
165/// RigidBody::Dynamic,
166/// Collider::capsule(0.5, 1.5),
167/// Mass(5.0),
168#[cfg_attr(feature = "2d", doc = " CenterOfMass::new(0.0, -0.5),")]
169#[cfg_attr(feature = "3d", doc = " CenterOfMass::new(0.0, -0.5, 0.0),")]
170/// ));
171/// # }
172/// ```
173///
174/// If the rigid body has child colliders, their mass properties will be combined for
175/// the total [`ComputedMass`], [`ComputedAngularInertia`], and [`ComputedCenterOfMass`].
176///
177/// ```
178#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
179#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
180/// # use bevy::prelude::*;
181/// #
182/// # fn setup(mut commands: Commands) {
183/// // Total mass: 10.0 + 5.0 = 15.0
184#[cfg_attr(
185 feature = "2d",
186 doc = "// Total center of mass: (10.0 * [0.0, -0.5] + 5.0 * [0.0, 4.0]) / (10.0 + 5.0) = [0.0, 1.0]"
187)]
188#[cfg_attr(
189 feature = "3d",
190 doc = "// Total center of mass: (10.0 * [0.0, -0.5, 0.0] + 5.0 * [0.0, 4.0, 0.0]) / (10.0 + 5.0) = [0.0, 1.0, 0.0]"
191)]
192/// commands.spawn((
193/// RigidBody::Dynamic,
194/// Collider::capsule(0.5, 1.5),
195/// Mass(10.0),
196#[cfg_attr(feature = "2d", doc = " CenterOfMass::new(0.0, -0.5),")]
197#[cfg_attr(feature = "3d", doc = " CenterOfMass::new(0.0, -0.5, 0.0),")]
198/// Transform::default(),
199/// ))
200/// .with_child((
201#[cfg_attr(feature = "2d", doc = " Collider::circle(1.0),")]
202#[cfg_attr(feature = "3d", doc = " Collider::sphere(1.0),")]
203/// Mass(5.0),
204/// Transform::from_xyz(0.0, 4.0, 0.0),
205/// ));
206/// # }
207/// ```
208///
209/// To prevent child entities from contributing to the total mass properties, use the [`NoAutoMass`],
210/// [`NoAutoAngularInertia`], and [`NoAutoCenterOfMass`] marker components.
211///
212/// ```
213#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
214#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
215/// # use bevy::prelude::*;
216/// #
217/// # fn setup(mut commands: Commands) {
218/// // Total mass: 10.0
219#[cfg_attr(feature = "2d", doc = "// Total center of mass: [0.0, -0.5]")]
220#[cfg_attr(feature = "3d", doc = "// Total center of mass: [0.0, -0.5, 0.0]")]
221/// commands.spawn((
222/// RigidBody::Dynamic,
223/// Collider::capsule(0.5, 1.5),
224/// Mass(10.0),
225#[cfg_attr(feature = "2d", doc = " CenterOfMass::new(0.0, -0.5),")]
226#[cfg_attr(feature = "3d", doc = " CenterOfMass::new(0.0, -0.5, 0.0),")]
227/// NoAutoMass,
228/// NoAutoCenterOfMass,
229/// Transform::default(),
230/// ))
231/// .with_child((
232#[cfg_attr(feature = "2d", doc = " Collider::circle(1.0),")]
233#[cfg_attr(feature = "3d", doc = " Collider::sphere(1.0),")]
234/// Mass(5.0),
235/// Transform::from_xyz(0.0, 4.0, 0.0),
236/// ));
237/// # }
238/// ```
239///
240/// See the [`mass_properties`] module for more information.
241///
242/// [mass]: mass_properties::components::Mass
243/// [angular inertia]: mass_properties::components::AngularInertia
244/// [center of mass]: mass_properties::components::CenterOfMass
245/// [mass properties]: mass_properties
246///
247/// # See More
248///
249/// - [Colliders](Collider)
250/// - [Gravity] and [gravity scale](GravityScale)
251/// - [Linear](LinearDamping) and [angular](AngularDamping) velocity damping
252/// - [Friction] and [restitution](Restitution) (bounciness)
253/// - [Lock translational and rotational axes](LockedAxes)
254/// - [Dominance]
255/// - [Continuous Collision Detection](dynamics::ccd)
256/// - [Speculative collision](dynamics::ccd#speculative-collision)
257/// - [Swept CCD](dynamics::ccd#swept-ccd)
258/// - [`Transform` interpolation and extrapolation](PhysicsInterpolationPlugin)
259/// - [Temporarily disabling a rigid body](RigidBodyDisabled)
260/// - [Automatic deactivation with sleeping](Sleeping)
261#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, Eq)]
262#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
263#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
264#[reflect(Debug, Component, Default, PartialEq)]
265#[require(
266 LinearVelocity,
267 AngularVelocity,
268 // TODO: Make these force components optional.
269 ExternalForce,
270 ExternalTorque,
271 ExternalImpulse,
272 ExternalAngularImpulse,
273 ComputedMass,
274 ComputedAngularInertia,
275 ComputedCenterOfMass,
276 // Currently required for solver internals.
277 // Some of these might be removed in the future.
278 AccumulatedTranslation,
279 PreSolveAccumulatedTranslation,
280 PreSolveLinearVelocity,
281 PreSolveAngularVelocity,
282 PreSolveRotation,
283 PreviousRotation,
284)]
285#[cfg_attr(feature = "3d", require(GlobalAngularInertia))]
286pub enum RigidBody {
287 /// Dynamic bodies are bodies that are affected by forces, velocity and collisions.
288 #[default]
289 Dynamic,
290
291 /// Static bodies are not affected by any forces, collisions or velocity, and they act as if they have an infinite mass and moment of inertia.
292 /// The only way to move a static body is to manually change its position.
293 ///
294 /// Collisions with static bodies will affect dynamic bodies, but not other static bodies or kinematic bodies.
295 ///
296 /// Static bodies are typically used for things like the ground, walls and any other objects that you don't want to move.
297 Static,
298
299 /// Kinematic bodies are bodies that are not affected by any external forces or collisions.
300 /// They will realistically affect colliding dynamic bodies, but not other kinematic bodies.
301 ///
302 /// Unlike static bodies, kinematic bodies can have velocity.
303 /// The engine doesn't modify the values of a kinematic body's components,
304 /// so you have full control of them.
305 Kinematic,
306}
307
308impl RigidBody {
309 /// Checks if the rigid body is dynamic.
310 pub fn is_dynamic(&self) -> bool {
311 *self == Self::Dynamic
312 }
313
314 /// Checks if the rigid body is static.
315 pub fn is_static(&self) -> bool {
316 *self == Self::Static
317 }
318
319 /// Checks if the rigid body is kinematic.
320 pub fn is_kinematic(&self) -> bool {
321 *self == Self::Kinematic
322 }
323}
324
325/// A query filter that selects rigid bodies that are neither disabled nor sleeping.
326pub(crate) type RigidBodyActiveFilter = (Without<RigidBodyDisabled>, Without<Sleeping>);
327
328/// A marker component that indicates that a [rigid body](RigidBody) is disabled
329/// and should not participate in the simulation. Disables velocity, forces, contact response,
330/// and attached joints.
331///
332/// This is useful for temporarily disabling a body without removing it from the world.
333/// To re-enable the body, simply remove this component.
334///
335/// Note that this component does *not* disable collision detection or spatial queries for colliders
336/// attached to the rigid body.
337///
338/// # Example
339///
340/// ```
341#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
342#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
343/// # use bevy::prelude::*;
344/// #
345/// #[derive(Component)]
346/// pub struct Character;
347///
348/// /// Disables physics for all rigid body characters, for example during cutscenes.
349/// fn disable_character_physics(
350/// mut commands: Commands,
351/// query: Query<Entity, (With<RigidBody>, With<Character>)>,
352/// ) {
353/// for entity in &query {
354/// commands.entity(entity).insert(RigidBodyDisabled);
355/// }
356/// }
357///
358/// /// Enables physics for all rigid body characters.
359/// fn enable_character_physics(
360/// mut commands: Commands,
361/// query: Query<Entity, (With<RigidBody>, With<Character>)>,
362/// ) {
363/// for entity in &query {
364/// commands.entity(entity).remove::<RigidBodyDisabled>();
365/// }
366/// }
367/// ```
368///
369/// # Related Components
370///
371/// - [`ColliderDisabled`]: Disables a collider.
372/// - [`JointDisabled`]: Disables a joint constraint.
373#[derive(Clone, Copy, Component, Reflect, Debug, Default)]
374#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
375#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
376#[reflect(Debug, Component, Default)]
377pub struct RigidBodyDisabled;
378
379/// Indicates that a [rigid body](RigidBody) is not simulated by the physics engine until woken up again.
380/// This is done to improve performance and to help prevent small jitter that is typically present in collisions.
381///
382/// Bodies are marked as sleeping when their linear and angular velocity is below the [`SleepingThreshold`] for a time
383/// indicated by [`DeactivationTime`]. A sleeping body is woken up when an active body interacts with it through
384/// collisions or other constraints, or when gravity changes, or when the body's
385/// position, rotation, velocity, or external forces are modified.
386///
387/// Sleeping can be disabled for specific entities with the [`SleepingDisabled`] component,
388/// or for all entities by setting the [`SleepingThreshold`] to a negative value.
389#[derive(Reflect, Clone, Copy, Component, Debug, Default)]
390#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
391#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
392#[reflect(Debug, Component, Default)]
393pub struct Sleeping;
394
395/// How long the velocity of the body has been below the [`SleepingThreshold`],
396/// i.e. how long the body has been able to sleep.
397///
398/// See [`Sleeping`] for further information.
399#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, From)]
400#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
401#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
402#[reflect(Debug, Component, Default, PartialEq)]
403pub struct TimeSleeping(pub Scalar);
404
405/// Indicates that the body can not be deactivated by the physics engine. See [`Sleeping`] for information about sleeping.
406#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, Eq, From)]
407#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
408#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
409#[reflect(Debug, Component, Default, PartialEq)]
410pub struct SleepingDisabled;
411
412/// Translation accumulated during the physics frame.
413/// Used primarily by solver internals.
414///
415/// When updating position during integration or constraint solving, the required translation
416/// is added to [`AccumulatedTranslation`], instead of [`Position`]. This improves numerical stability
417/// of the simulation, especially for bodies far away from world origin.
418///
419/// At the end of each physics frame, the actual [`Position`] is updated in [`SolverSet::ApplyTranslation`].
420#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
421#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
422#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
423#[reflect(Debug, Component, Default, PartialEq)]
424pub struct AccumulatedTranslation(pub Vector);
425
426/// The linear velocity of a [rigid body](RigidBody), typically in meters per second.
427///
428/// # Example
429///
430/// ```
431#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
432#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
433/// use bevy::prelude::*;
434///
435/// # #[cfg(feature = "f32")]
436/// fn accelerate_linear(mut query: Query<&mut LinearVelocity>, time: Res<Time>) {
437/// let delta_secs = time.delta_secs();
438/// for mut linear_velocity in &mut query {
439/// // Accelerate the entity towards +X at `2.0` units per second squared.
440/// linear_velocity.x += 2.0 * delta_secs;
441/// }
442/// }
443/// # #[cfg(feature = "f64")]
444/// # fn main() {}
445/// ```
446///
447/// # Related Components
448///
449/// - [`AngularVelocity`]: The angular velocity of a body.
450/// - [`ExternalForce`]: Applies a force to a dynamic body.
451/// - [`LinearDamping`]: Reduces the linear velocity of a body over time, similar to air resistance.
452/// - [`MaxLinearSpeed`]: Clamps the linear velocity of a body.
453#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
454#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
455#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
456#[reflect(Debug, Component, Default, PartialEq)]
457pub struct LinearVelocity(pub Vector);
458
459impl LinearVelocity {
460 /// Zero linear velocity.
461 pub const ZERO: LinearVelocity = LinearVelocity(Vector::ZERO);
462}
463
464/// The maximum linear speed of a [rigid body](RigidBody), clamping the [`LinearVelocity`],
465/// typically in meters per second.
466///
467/// This can be useful for limiting how fast bodies can move, and can help control behavior and prevent instability.
468///
469/// # Example
470///
471/// ```
472#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
473#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
474/// use bevy::prelude::*;
475///
476/// // Spawn a dynamic body with linear velocity clamped to `100.0` units per second.
477/// fn setup(mut commands: Commands) {
478/// commands.spawn((RigidBody::Dynamic, MaxLinearSpeed(100.0)));
479/// }
480/// ```
481#[derive(Reflect, Clone, Copy, Component, Debug, Deref, DerefMut, PartialEq, From)]
482#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
483#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
484#[reflect(Debug, Component, Default, PartialEq)]
485#[doc(alias = "MaxLinearVelocity")]
486pub struct MaxLinearSpeed(pub Scalar);
487
488impl Default for MaxLinearSpeed {
489 fn default() -> Self {
490 Self(Scalar::INFINITY)
491 }
492}
493
494/// The maximum angular speed of a [rigid body](RigidBody), clamping the [`AngularVelocity`],
495/// in radians per second.
496///
497/// This can be useful for limiting how fast bodies can rotate, and can help control behavior and prevent instability.
498///
499/// # Example
500///
501/// ```
502#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
503#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
504/// use bevy::prelude::*;
505///
506/// // Spawn a dynamic body with angular velocity clamped to `20.0` radians per second.
507/// fn setup(mut commands: Commands) {
508/// commands.spawn((RigidBody::Dynamic, MaxAngularSpeed(20.0)));
509/// }
510/// ```
511#[derive(Reflect, Clone, Copy, Component, Debug, Deref, DerefMut, PartialEq, From)]
512#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
513#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
514#[reflect(Debug, Component, Default, PartialEq)]
515#[doc(alias = "MaxAngularVelocity")]
516pub struct MaxAngularSpeed(pub Scalar);
517
518impl Default for MaxAngularSpeed {
519 fn default() -> Self {
520 Self(Scalar::INFINITY)
521 }
522}
523
524/// The linear velocity of a [rigid body](RigidBody) before the velocity solve is performed.
525#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
526#[reflect(Component)]
527pub(crate) struct PreSolveLinearVelocity(pub Vector);
528
529/// The angular velocity of a [rigid body](RigidBody) in radians per second.
530/// Positive values will result in counterclockwise rotation.
531///
532/// # Example
533///
534/// ```
535/// use avian2d::prelude::*;
536/// use bevy::prelude::*;
537///
538/// # #[cfg(feature = "f32")]
539/// fn accelerate_angular(mut query: Query<&mut AngularVelocity>, time: Res<Time>) {
540/// let delta_secs = time.delta_secs();
541/// for mut angular_velocity in &mut query {
542/// // Accelerate rotation counterclockwise at `0.5` radians per second squared.
543/// angular_velocity.0 += 0.5 * delta_secs;
544/// }
545/// }
546/// # #[cfg(feature = "f64")]
547/// # fn main() {}
548/// ```
549///
550/// # Related Components
551///
552/// - [`LinearVelocity`]: The linear velocity of a body.
553/// - [`ExternalTorque`]: Applies a torque to a dynamic body.
554/// - [`AngularDamping`]: Reduces the angular velocity of a body over time, similar to air resistance.
555/// - [`MaxAngularSpeed`]: Clamps the angular velocity of a body.
556#[cfg(feature = "2d")]
557#[derive(Reflect, Clone, Copy, Deref, DerefMut, Component, Debug, Default, PartialEq, From)]
558#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
559#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
560#[reflect(Debug, Component, Default, PartialEq)]
561pub struct AngularVelocity(pub Scalar);
562
563/// The angular velocity of a [rigid body](RigidBody), represented as a rotation axis
564/// multiplied by the angular speed in radians per second.
565///
566/// # Example
567///
568/// ```
569/// use avian3d::prelude::*;
570/// use bevy::prelude::*;
571///
572/// # #[cfg(feature = "f32")]
573/// fn accelerate_angular(mut query: Query<&mut AngularVelocity>, time: Res<Time>) {
574/// let delta_secs = time.delta_secs();
575/// for mut angular_velocity in &mut query {
576/// // Accelerate rotation about the Z axis at `0.5` radians per second squared.
577/// angular_velocity.z += 0.5 * delta_secs;
578/// }
579/// }
580/// # #[cfg(feature = "f64")]
581/// # fn main() {}
582/// ```
583///
584/// # Related Components
585///
586/// - [`LinearVelocity`]: The linear velocity of a body.
587/// - [`ExternalTorque`]: Applies a torque to a dynamic body.
588/// - [`AngularDamping`]: Reduces the angular velocity of a body over time, similar to air resistance.
589/// - [`MaxAngularSpeed`]: Clamps the angular velocity of a body.
590#[cfg(feature = "3d")]
591#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
592#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
593#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
594#[reflect(Debug, Component, Default, PartialEq)]
595pub struct AngularVelocity(pub Vector);
596
597impl AngularVelocity {
598 /// Zero angular velocity.
599 #[cfg(feature = "2d")]
600 pub const ZERO: AngularVelocity = AngularVelocity(0.0);
601 /// Zero angular velocity.
602 #[cfg(feature = "3d")]
603 pub const ZERO: AngularVelocity = AngularVelocity(Vector::ZERO);
604}
605
606/// The angular velocity of a [rigid body](RigidBody) in radians per second, before
607/// the velocity solve is performed. Positive values will result in counterclockwise rotation.
608#[cfg(feature = "2d")]
609#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, From)]
610#[reflect(Component)]
611pub(crate) struct PreSolveAngularVelocity(pub Scalar);
612
613/// The angular velocity of a [rigid body](RigidBody) as a rotation axis
614/// multiplied by the angular speed in radians per second, before the velocity solve is performed.
615#[cfg(feature = "3d")]
616#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
617#[reflect(Component)]
618pub(crate) struct PreSolveAngularVelocity(pub Vector);
619
620/// Controls how [gravity](Gravity) affects a specific [rigid body](RigidBody).
621///
622/// A gravity scale of `0.0` will disable gravity, while `2.0` will double the gravity.
623/// Using a negative value will flip the direction of the gravity.
624///
625/// # Example
626///
627/// ```
628#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
629#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
630/// use bevy::prelude::*;
631///
632/// // Spawn a dynamic body with `1.5` times the normal gravity.
633/// fn setup(mut commands: Commands) {
634/// commands.spawn((RigidBody::Dynamic, GravityScale(1.5)));
635/// }
636/// ```
637#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Deref, DerefMut, From)]
638#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
639#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
640#[reflect(Debug, Component, Default, PartialEq)]
641pub struct GravityScale(pub Scalar);
642
643impl Default for GravityScale {
644 fn default() -> Self {
645 Self(1.0)
646 }
647}
648
649/// Automatically slows down a dynamic [rigid body](RigidBody), decreasing its
650/// [linear velocity](LinearVelocity) each frame. This can be used to simulate air resistance.
651///
652/// The default linear damping coefficient is `0.0`, which corresponds to no damping.
653///
654/// # Example
655///
656/// ```
657#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
658#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
659/// use bevy::prelude::*;
660///
661/// fn setup(mut commands: Commands) {
662/// commands.spawn((RigidBody::Dynamic, LinearDamping(0.8)));
663/// }
664/// ```
665#[derive(
666 Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Default, Deref, DerefMut, From,
667)]
668#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
669#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
670#[reflect(Debug, Component, Default, PartialEq)]
671pub struct LinearDamping(pub Scalar);
672
673/// Automatically slows down a dynamic [rigid body](RigidBody), decreasing its
674/// [angular velocity](AngularVelocity) each frame. This can be used to simulate air resistance.
675///
676/// The default angular damping coefficient is `0.0`, which corresponds to no damping.
677///
678/// # Example
679///
680/// ```
681#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
682#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
683/// use bevy::prelude::*;
684///
685/// fn setup(mut commands: Commands) {
686/// commands.spawn((RigidBody::Dynamic, AngularDamping(1.6)));
687/// }
688/// ```
689#[derive(
690 Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Default, Deref, DerefMut, From,
691)]
692#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
693#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
694#[reflect(Debug, Component, Default, PartialEq)]
695pub struct AngularDamping(pub Scalar);
696
697/// **Dominance** allows [dynamic rigid bodies](RigidBody::Dynamic) to dominate
698/// each other during physical interactions.
699///
700/// The body with a higher dominance acts as if it had infinite mass, and will be unaffected during
701/// collisions and other interactions, while the other body will be affected normally.
702///
703/// The dominance must be between `-127` and `127`, and the default value is `0`.
704/// Note that static and kinematic bodies will always have a higher dominance value
705/// than dynamic bodies regardless of the value of this component.
706///
707/// # Example
708///
709/// ```
710#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
711#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
712/// use bevy::prelude::*;
713///
714/// // Player dominates all dynamic bodies with a dominance lower than `5`.
715/// fn spawn_player(mut commands: Commands) {
716/// commands.spawn((
717/// RigidBody::Dynamic,
718/// Collider::capsule(0.4, 1.0),
719/// Dominance(5),
720/// ));
721/// }
722/// ```
723#[rustfmt::skip]
724#[derive(Component, Reflect, Debug, Clone, Copy, Default, Deref, DerefMut, From, PartialEq, PartialOrd, Eq, Ord)]
725#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
726#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
727#[reflect(Debug, Component, Default, PartialEq)]
728pub struct Dominance(pub i8);