avian3d/dynamics/integrator/mod.rs
1//! Applies forces and velocities to bodies in order to move them according to the equations of motion
2//! using numerical integration.
3//!
4//! See [`IntegratorPlugin`].
5
6use crate::{
7 dynamics::solver::solver_body::SolverBodyFlags,
8 prelude::*,
9 utils::{MIN_PAR_ITER_ENTITIES, ParallelQueryForEach, par_for_each},
10};
11use bevy::{
12 ecs::{intern::Interned, query::QueryData, schedule::ScheduleLabel},
13 prelude::*,
14};
15use dynamics::solver::SolverDiagnostics;
16
17use super::solver::solver_body::{SolverBodies, SolverBody, SolverBodyIndex};
18
19/// Integrates Newton's 2nd law of motion, applying forces and moving entities according to their velocities.
20///
21/// This acts as a prediction for the next positions and orientations of the bodies. The [solver](dynamics::solver)
22/// corrects these predicted positions to take constraints like contacts and joints into account.
23///
24/// Currently, only the [semi-implicit (symplectic) Euler](https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)
25/// integration scheme is supported. It is the standard for game physics, being stable, efficient, and sufficiently accurate.
26///
27/// See [`IntegrationSystems`] for the system sets used by this plugin.
28pub struct IntegratorPlugin {
29 schedule: Interned<dyn ScheduleLabel>,
30}
31
32impl IntegratorPlugin {
33 /// Creates an [`IntegratorPlugin`] with the schedule that the integration systems should run in.
34 ///
35 /// The default schedule is [`SubstepSchedule`].
36 pub fn new(schedule: impl ScheduleLabel) -> Self {
37 Self {
38 schedule: schedule.intern(),
39 }
40 }
41}
42
43impl Default for IntegratorPlugin {
44 fn default() -> Self {
45 Self::new(SubstepSchedule)
46 }
47}
48
49impl Plugin for IntegratorPlugin {
50 fn build(&self, app: &mut App) {
51 // Add `VelocityIntegrationData` to all bodies that have a solver body.
52 app.register_required_components::<SolverBodyIndex, VelocityIntegrationData>();
53
54 app.init_resource::<Gravity>();
55
56 app.configure_sets(
57 PhysicsSchedule,
58 (
59 IntegrationSystems::UpdateVelocityIncrements
60 .in_set(SolverSystems::PreSubstep)
61 .before(IntegrationSystems::Velocity),
62 IntegrationSystems::ClearVelocityIncrements
63 .in_set(SolverSystems::PostSubstep)
64 .after(IntegrationSystems::Velocity),
65 ),
66 );
67
68 app.add_systems(
69 PhysicsSchedule,
70 (
71 pre_process_velocity_increments
72 .in_set(IntegrationSystems::UpdateVelocityIncrements),
73 clear_velocity_increments.in_set(IntegrationSystems::ClearVelocityIncrements),
74 ),
75 );
76
77 app.configure_sets(
78 self.schedule.intern(),
79 (IntegrationSystems::Velocity, IntegrationSystems::Position).chain(),
80 );
81
82 app.add_systems(
83 self.schedule.intern(),
84 (
85 (integrate_velocities, clamp_velocities)
86 .chain()
87 .in_set(IntegrationSystems::Velocity),
88 integrate_positions.in_set(IntegrationSystems::Position),
89 ),
90 );
91 }
92}
93
94/// System sets for position and velocity integration,
95/// applying forces and moving bodies based on velocity.
96#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
97pub enum IntegrationSystems {
98 /// Applies gravity and locked axes to the linear and angular velocity increments of bodies,
99 /// and multiplies them by the substep delta time to get the final per-substep increments.
100 ///
101 /// Runs in the [`PhysicsSchedule`], in [`SolverSystems::PreSubstep`].
102 UpdateVelocityIncrements,
103 /// Applies velocity increments to the linear and angular velocities of bodies.
104 ///
105 /// Typically runs in the [`SubstepSchedule`], in [`IntegrationSystems::Velocity`].
106 Velocity,
107 /// Moves bodies based on their current velocities and the physics time step.
108 ///
109 /// Typically runs in the [`SubstepSchedule`], in [`IntegrationSystems::Position`].
110 Position,
111 /// Clears the velocity increments of bodies after the substepping loop.
112 ///
113 /// Runs in the [`PhysicsSchedule`], in [`SolverSystems::PostSubstep`].
114 ClearVelocityIncrements,
115}
116
117/// A deprecated alias for [`IntegrationSystems`].
118#[deprecated(since = "0.4.0", note = "Renamed to `IntegrationSystems`")]
119pub type IntegrationSet = IntegrationSystems;
120
121/// A resource for the global gravitational acceleration.
122///
123/// The default is an acceleration of 9.81 m/s^2 pointing down, which is approximate to the gravitational
124/// acceleration near Earth's surface. Note that if you are using pixels as length units in 2D,
125/// this gravity will be tiny. You should modify the gravity to fit your application.
126///
127/// You can also control how gravity affects a specific [rigid body](RigidBody) using the [`GravityScale`]
128/// component. The magnitude of the gravity will be multiplied by this scaling factor.
129///
130/// # Example
131///
132/// ```no_run
133#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
134#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
135/// use bevy::prelude::*;
136///
137/// fn main() {
138/// App::new()
139/// .add_plugins((DefaultPlugins, PhysicsPlugins::default()))
140#[cfg_attr(
141 feature = "2d",
142 doc = " .insert_resource(Gravity(Vec2::NEG_Y * 100.0))"
143)]
144#[cfg_attr(
145 feature = "3d",
146 doc = " .insert_resource(Gravity(Vec3::NEG_Y * 19.6))"
147)]
148/// .run();
149/// }
150/// ```
151///
152/// You can also modify gravity while the app is running.
153#[derive(Reflect, Resource, Debug)]
154#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
155#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
156#[reflect(Debug, Resource)]
157pub struct Gravity(pub Vector);
158
159impl Default for Gravity {
160 fn default() -> Self {
161 Self(Vector::Y * -9.81)
162 }
163}
164
165impl Gravity {
166 /// Zero gravity.
167 pub const ZERO: Gravity = Gravity(Vector::ZERO);
168}
169
170/// A marker component for bodies that use custom velocity integration.
171///
172/// This means that gravity, damping, and external forces will not be applied automatically.
173/// You are responsible for applying all forces and updating velocities manually.
174///
175/// Exceptions include:
176///
177/// - Contact impulses and joint impulses for dynamic bodies
178/// - Impulses applied via [`Forces`]
179#[derive(Component, Debug, Default, Reflect, Clone, Copy)]
180#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
181#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
182#[reflect(Component, Debug, Default)]
183pub struct CustomVelocityIntegration;
184
185/// A marker component for bodies that use custom position integration.
186///
187/// This means that the body's position and rotation will not be updated automatically
188/// based on velocity. You are responsible for updating the position and rotation manually.
189///
190/// This can be useful for implementing kinematic bodies that are moved according to custom logic,
191/// such as with [`MoveAndSlide`].
192#[derive(Component, Debug, Default, Reflect, Clone, Copy)]
193#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
194#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
195#[reflect(Component, Debug, Default)]
196pub struct CustomPositionIntegration;
197
198/// Pre-computed data for speeding up velocity integration.
199///
200/// This includes:
201///
202/// - Velocity increments for [`Gravity`].
203/// - Velocity increments for [`ConstantForce`], [`ConstantTorque`], [`ConstantLinearAcceleration`], and [`ConstantAngularAcceleration`].
204/// - Velocity increments for forces, torques, and accelerations applied using [`Forces`].
205/// - Cached operands for applying linear and angular velocity damping.
206///
207/// The values are computed once per time step, and applied to the body at each substep
208/// with basic addition and multiplication. This moves the more expensive operations
209/// and branching out of the substepping loop.
210// -----------------------
211// 20 bytes in 2D with f32
212// 32 bytes in 3D with f32
213#[derive(Component, Debug, Default, PartialEq, Reflect)]
214#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
215#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
216#[reflect(Component, Debug, Default, PartialEq)]
217pub struct VelocityIntegrationData {
218 /// The linear velocity increment to be applied to the body at each substep.
219 ///
220 /// **Note:** This is treated as linear acceleration until [`IntegrationSystems::UpdateVelocityIncrements`].
221 /// where it is multiplied by the time step to get the corresponding velocity increment.
222 pub linear_increment: Vector,
223 /// The angular velocity increment to be applied to the body at each substep.
224 ///
225 /// **Note:** This is treated as angular acceleration until [`IntegrationSystems::UpdateVelocityIncrements`].
226 /// where it is multiplied by the time step to get the corresponding velocity increment.
227 pub angular_increment: AngularVector,
228 /// The right-hand side of the linear damping equation,
229 /// `1 / (1 + dt * c)`, where `c` is the damping coefficient.
230 pub linear_damping_rhs: f32,
231 /// The right-hand side of the angular damping equation,
232 /// `1 / (1 + dt * c)`, where `c` is the damping coefficient.
233 pub angular_damping_rhs: f32,
234}
235
236impl VelocityIntegrationData {
237 /// Applies a given linear acceleration to the body.
238 pub fn apply_linear_acceleration(&mut self, acceleration: Vector) {
239 self.linear_increment += acceleration;
240 }
241
242 /// Applies a given angular acceleration to the body.
243 pub fn apply_angular_acceleration(&mut self, acceleration: AngularVector) {
244 self.angular_increment += acceleration;
245 }
246
247 /// Updates the cached right-hand side of the linear damping equation,
248 /// `1 / (1 + dt * c)`, where `c` is the damping coefficient.
249 pub fn update_linear_damping_rhs(&mut self, damping_coefficient: f32, delta_secs: f32) {
250 self.linear_damping_rhs = 1.0 / (1.0 + delta_secs * damping_coefficient);
251 }
252
253 /// Updates the cached right-hand side of the angular damping equation,
254 /// `1 / (1 + dt * c)`, where `c` is the damping coefficient.
255 pub fn update_angular_damping_rhs(&mut self, damping_coefficient: f32, delta_secs: f32) {
256 self.angular_damping_rhs = 1.0 / (1.0 + delta_secs * damping_coefficient);
257 }
258}
259
260/// Applies gravity and locked axes to the linear and angular velocity increments of bodies.
261pub fn pre_process_velocity_increments(
262 mut bodies: Query<(
263 &RigidBody,
264 &mut VelocityIntegrationData,
265 Option<&LinearDamping>,
266 Option<&AngularDamping>,
267 Option<&GravityScale>,
268 Option<&LockedAxes>,
269 )>,
270 gravity: Res<Gravity>,
271 time: Res<Time<Substeps>>,
272 mut diagnostics: ResMut<SolverDiagnostics>,
273) {
274 let start = crate::utils::Instant::now();
275
276 let delta_secs = time.delta_secs();
277
278 // TODO: Do we want to skip kinematic bodies here?
279 bodies.par_for_each_mut(
280 MIN_PAR_ITER_ENTITIES,
281 |(rb, mut integration, lin_damping, ang_damping, gravity_scale, locked_axes)| {
282 if !rb.is_dynamic() {
283 // Skip non-dynamic bodies.
284 return;
285 }
286
287 let locked_axes = locked_axes.map_or(LockedAxes::default(), |locked_axes| *locked_axes);
288
289 // Update the cached right-hand side of the velocity damping equation,
290 // `1 / (1 + dt * c)`, where `c` is the damping coefficient.
291 let lin_damping = lin_damping.map_or(0.0, |damping| damping.0);
292 let ang_damping = ang_damping.map_or(0.0, |damping| damping.0);
293 integration.update_linear_damping_rhs(lin_damping, delta_secs);
294 integration.update_angular_damping_rhs(ang_damping, delta_secs);
295
296 // NOTE: The `ForcePlugin` handles the application of external forces and torques.
297 // NOTE: The velocity increments are treated as accelerations at this point.
298
299 // Apply gravity.
300 integration.linear_increment += gravity.0 * gravity_scale.map_or(1.0, |scale| scale.0);
301
302 // Apply locked axes.
303 integration.linear_increment = locked_axes.apply_to_vec(integration.linear_increment);
304 integration.angular_increment =
305 locked_axes.apply_to_angular_velocity(integration.angular_increment);
306
307 // The velocity increments are treated as accelerations until this point.
308 // Multiply by the time step to get the final velocity increments.
309 integration.linear_increment *= delta_secs;
310 integration.angular_increment *= delta_secs;
311 },
312 );
313
314 diagnostics.update_velocity_increments += start.elapsed();
315}
316
317/// Clears the velocity increments of bodies after the substepping loop.
318fn clear_velocity_increments(
319 mut bodies: Query<&mut VelocityIntegrationData, With<SolverBodyIndex>>,
320 mut diagnostics: ResMut<SolverDiagnostics>,
321) {
322 let start = crate::utils::Instant::now();
323
324 bodies.par_for_each_mut(MIN_PAR_ITER_ENTITIES, |mut integration| {
325 integration.linear_increment = Vector::ZERO;
326 integration.angular_increment = default();
327 });
328
329 diagnostics.update_velocity_increments += start.elapsed();
330}
331
332#[derive(QueryData)]
333#[query_data(mutable)]
334#[doc(hidden)]
335pub struct VelocityIntegrationQuery {
336 index: &'static SolverBodyIndex,
337 integration: &'static mut VelocityIntegrationData,
338 #[cfg(feature = "3d")]
339 angular_inertia: &'static ComputedAngularInertia,
340 #[cfg(feature = "3d")]
341 rotation: &'static Rotation,
342}
343
344/// Integrates the velocities of bodies by applying velocity increments and damping.
345pub fn integrate_velocities(
346 mut solver_bodies: ResMut<SolverBodies>,
347 mut bodies: Query<
348 VelocityIntegrationQuery,
349 (RigidBodyActiveFilter, Without<CustomVelocityIntegration>),
350 >,
351 mut diagnostics: ResMut<SolverDiagnostics>,
352 #[cfg(feature = "3d")] time: Res<Time>,
353) {
354 let start = crate::utils::Instant::now();
355
356 #[cfg(feature = "3d")]
357 let delta_secs = time.delta_secs();
358
359 let access = solver_bodies.access();
360
361 bodies.par_for_each_mut(MIN_PAR_ITER_ENTITIES, |body| {
362 // SAFETY: Each entity has a unique solver body index, so the accessed bodies are disjoint.
363 let solver_body = unsafe { access.body_unchecked_mut(*body.index) };
364
365 if solver_body.flags.is_kinematic() {
366 // Skip kinematic bodies.
367 return;
368 }
369
370 // Apply velocity damping.
371 solver_body.linear_velocity *= body.integration.linear_damping_rhs;
372 solver_body.angular_velocity *= body.integration.angular_damping_rhs;
373
374 // Apply velocity increments.
375 solver_body.linear_velocity += body.integration.linear_increment;
376 solver_body.angular_velocity += body.integration.angular_increment;
377
378 #[cfg(feature = "3d")]
379 {
380 if solver_body.is_gyroscopic() {
381 // TODO: Should this be opt-in with a `GyroscopicMotion` component?
382 // TODO: It's a bit unfortunate that this has to run in the substepping loop
383 // rather than pre-computing the velocity increments once per time step.
384 // This needs to be done because the gyroscopic torque relies on up-to-date rotations
385 // and world-space angular inertia tensors. Omitting the change in orientation would
386 // lead to worse accuracy and angular momentum not being conserved.
387 let rotation = solver_body.delta_rotation * Rot::from(*body.rotation);
388 solve_gyroscopic_torque(
389 &mut solver_body.angular_velocity,
390 rotation,
391 body.angular_inertia,
392 delta_secs,
393 );
394 }
395 }
396 });
397
398 diagnostics.integrate_velocities += start.elapsed();
399}
400
401/// Applies the effects of gyroscopic motion to the given angular velocity.
402///
403/// Gyroscopic motion is the tendency of a rotating object to maintain its axis of rotation
404/// unless acted upon by an external torque. It manifests as objects with non-uniform angular
405/// inertia tensors seemingly wobbling as they spin in the air or on the ground.
406///
407/// Gyroscopic motion is important for realistic spinning behavior, and for simulating
408/// gyroscopic phenomena such as the Dzhanibekov effect.
409#[cfg(feature = "3d")]
410#[inline]
411pub fn solve_gyroscopic_torque(
412 ang_vel: &mut Vector,
413 rotation: Quat,
414 local_inertia: &ComputedAngularInertia,
415 delta_secs: f32,
416) {
417 // References:
418 // - The "Gyroscopic Motion" section of Erin Catto's GDC 2015 slides on Numerical Methods.
419 // https://box2d.org/files/ErinCatto_NumericalMethods_GDC2015.pdf
420 // - Jolt Physics - MotionProperties::ApplyGyroscopicForceInternal
421 // https://github.com/jrouwe/JoltPhysics/blob/d497df2b9b0fa9aaf41295e1406079c23148232d/Jolt/Physics/Body/MotionProperties.inl#L102
422 //
423 // Erin Catto's GDC presentation suggests using implicit Euler for gyroscopic torque,
424 // as semi-implicit Euler can easily blow up with larger time steps due to extrapolating velocity.
425 // The extrapolation diverges quickly because gyroscopic torque is quadratic in the angular velocity.
426 //
427 // However, implicit Euler is measurably more expensive than semi-implicit Euler.
428 // We instead take inspiration from Jolt, and use semi-implicit Euler integration,
429 // clamping the magnitude of the angular momentum to remain the same.
430 // This is efficient, prevents energy from being introduced into the system,
431 // and produces reasonably accurate results for game purposes.
432
433 // Convert angular velocity to body space so that we can use the local angular inertia.
434 let local_ang_vel = rotation.inverse() * *ang_vel;
435
436 // Compute body-space angular momentum.
437 let local_momentum = local_inertia.tensor() * local_ang_vel;
438
439 // The gyroscopic torque is given by:
440 //
441 // T = -ω x I ω = -ω x L
442 //
443 // where ω is the angular velocity, I is the angular inertia tensor,
444 // and L is the angular momentum.
445 //
446 // The change in angular momentum is given by:
447 //
448 // ΔL = T Δt = -ω x L Δt
449 //
450 // Thus, we can compute the new angular momentum as:
451 //
452 // L' = L + ΔL = L - Δt (ω x L)
453 let mut new_local_momentum = local_momentum - delta_secs * local_ang_vel.cross(local_momentum);
454
455 // Make sure the magnitude of the angular momentum remains the same to avoid introducing
456 // energy into the system due to the extrapolation done by semi-implicit Euler integration.
457 let new_local_momentum_length_squared = new_local_momentum.length_squared();
458 if new_local_momentum_length_squared == 0.0 {
459 *ang_vel = Vector::ZERO;
460 return;
461 }
462 new_local_momentum *=
463 (local_momentum.length_squared() / new_local_momentum_length_squared).sqrt();
464
465 // Convert back to world-space angular velocity.
466 let local_inverse_inertia = local_inertia.inverse();
467 *ang_vel = rotation * (local_inverse_inertia * new_local_momentum);
468}
469
470// NOTE: If the majority of bodies have clamped velocities, it would be more efficient
471// to do this in `integrate_velocities` rather than in a separate system.
472// By doing this in a separate system, we're optimizing for the assumption
473// that only some bodies have clamped velocities.
474/// Clamps the velocities of bodies to [`MaxLinearSpeed`] and [`MaxAngularSpeed`].
475fn clamp_velocities(
476 mut solver_bodies: ResMut<SolverBodies>,
477 mut bodies: ParamSet<(
478 Query<(&SolverBodyIndex, &MaxLinearSpeed)>,
479 Query<(&SolverBodyIndex, &MaxAngularSpeed)>,
480 )>,
481 mut diagnostics: ResMut<SolverDiagnostics>,
482) {
483 let start = crate::utils::Instant::now();
484
485 let access = solver_bodies.access();
486
487 // Clamp linear velocity.
488 bodies.p0().iter().for_each(|(index, max_speed)| {
489 // SAFETY: Each entity has a unique solver body index, so the accessed bodies are disjoint.
490 let body = unsafe { access.body_unchecked_mut(*index) };
491 let linear_speed_squared = body.linear_velocity.length_squared();
492 if linear_speed_squared > max_speed.0 * max_speed.0 {
493 body.linear_velocity *= max_speed.0 / linear_speed_squared.sqrt();
494 }
495 });
496
497 // Clamp angular velocity.
498 bodies.p1().iter().for_each(|(index, max_speed)| {
499 // SAFETY: Each entity has a unique solver body index, so the accessed bodies are disjoint.
500 let body = unsafe { access.body_unchecked_mut(*index) };
501 #[cfg(feature = "2d")]
502 if body.angular_velocity.abs() > max_speed.0 {
503 body.angular_velocity = max_speed.copysign(body.angular_velocity);
504 }
505 #[cfg(feature = "3d")]
506 {
507 let angular_speed_squared = body.angular_velocity.length_squared();
508 if angular_speed_squared > max_speed.0 * max_speed.0 {
509 body.angular_velocity *= max_speed.0 / angular_speed_squared.sqrt();
510 }
511 }
512 });
513
514 diagnostics.integrate_velocities += start.elapsed();
515}
516
517/// Integrates the positions of bodies based on their velocities and the time step.
518pub fn integrate_positions(
519 mut bodies: ResMut<SolverBodies>,
520 time: Res<Time>,
521 mut diagnostics: ResMut<SolverDiagnostics>,
522) {
523 let start = crate::utils::Instant::now();
524
525 let delta_secs = time.delta_secs();
526
527 par_for_each(bodies.bodies_mut(), 4096, |_index, body| {
528 // Skip bodies that have custom position integration.
529 if body
530 .flags
531 .contains(SolverBodyFlags::CUSTOM_POSITION_INTEGRATION)
532 {
533 return;
534 }
535
536 let SolverBody {
537 linear_velocity,
538 angular_velocity,
539 delta_position,
540 delta_rotation,
541 ..
542 } = body;
543
544 *delta_position += *linear_velocity * delta_secs;
545 #[cfg(feature = "2d")]
546 {
547 // Note: We should probably use `add_angle_fast` here
548 *delta_rotation = Rot2::radians(*angular_velocity * delta_secs) * *delta_rotation;
549 }
550 #[cfg(feature = "3d")]
551 {
552 *delta_rotation =
553 Quat::from_scaled_axis(*angular_velocity * delta_secs) * *delta_rotation;
554 }
555 });
556
557 diagnostics.integrate_positions += start.elapsed();
558}
559
560#[cfg(test)]
561mod tests {
562 use core::time::Duration;
563
564 use approx::assert_relative_eq;
565
566 use crate::prelude::*;
567 use bevy::{mesh::MeshPlugin, prelude::*, time::TimeUpdateStrategy};
568
569 fn create_app() -> App {
570 let mut app = App::new();
571 app.add_plugins((
572 MinimalPlugins,
573 PhysicsPlugins::default(),
574 TransformPlugin,
575 #[cfg(feature = "bevy_scene")]
576 AssetPlugin::default(),
577 #[cfg(feature = "bevy_scene")]
578 bevy::scene::ScenePlugin,
579 MeshPlugin,
580 ));
581 app
582 }
583
584 #[test]
585 fn semi_implicit_euler() {
586 let mut app = create_app();
587 app.insert_resource(SubstepCount(1));
588 app.finish();
589
590 let body_entity = app
591 .world_mut()
592 .spawn((
593 RigidBody::Dynamic,
594 #[cfg(feature = "2d")]
595 {
596 (
597 MassPropertiesBundle::from_shape(&Rectangle::from_length(1.0), 1.0),
598 AngularVelocity(2.0),
599 )
600 },
601 #[cfg(feature = "3d")]
602 {
603 (
604 MassPropertiesBundle::from_shape(&Cuboid::from_length(1.0), 1.0),
605 AngularVelocity(Vec3::Z * 2.0),
606 )
607 },
608 ))
609 .id();
610
611 // Step by 100 steps of 0.1 seconds.
612 app.insert_resource(Time::from_hz(10.0));
613 app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_secs_f64(
614 1.0 / 10.0,
615 )));
616
617 // Initialize the app.
618 app.update();
619
620 for _ in 0..100 {
621 app.update();
622 }
623
624 // Get the body after the simulation.
625 let entity_ref = app.world_mut().entity(body_entity);
626 let position = entity_ref.get::<Position>().unwrap().0;
627 let rotation = *entity_ref.get::<Rotation>().unwrap();
628 let linear_velocity = entity_ref.get::<LinearVelocity>().unwrap().0;
629 let angular_velocity = entity_ref.get::<AngularVelocity>().unwrap().0;
630
631 // Euler methods have some precision issues, but this seems weirdly inaccurate.
632 assert_relative_eq!(position, RVector::NEG_Y * 490.5, epsilon = 10.0);
633
634 #[cfg(feature = "2d")]
635 assert_relative_eq!(
636 rotation.as_radians(),
637 Rotation::radians(20.0).as_radians(),
638 epsilon = 0.00001
639 );
640 #[cfg(feature = "3d")]
641 assert_relative_eq!(rotation.0, Quat::from_rotation_z(20.0), epsilon = 0.01);
642
643 assert_relative_eq!(linear_velocity, Vector::NEG_Y * 98.1, epsilon = 0.0001);
644 #[cfg(feature = "2d")]
645 assert_relative_eq!(angular_velocity, 2.0, epsilon = 0.00001);
646 #[cfg(feature = "3d")]
647 assert_relative_eq!(angular_velocity, Vector::Z * 2.0, epsilon = 0.00001);
648 }
649}