Iterate over combinations of entities
Bevy version: 0.14Last updated:
Use iter_combinations_mut()
which will zip up all combinations of components.
fn interact_bodies(
mut query: Query<(&Mass, &GlobalTransform, &mut Acceleration)>,
) {
let mut iter = query.iter_combinations_mut();
while let Some(
[(Mass(m1), transform1, mut acc1), (Mass(m2), transform2, mut acc2)],
) = iter.fetch_next()
{
let delta = transform2.translation() - transform1.translation();
let distance_sq: f32 = delta.length_squared();
let f = GRAVITY_CONSTANT / distance_sq;
let force_unit_mass = delta * f;
acc1.0 += force_unit_mass * *m2;
acc2.0 -= force_unit_mass * *m1;
}
}
This can be particularly useful when building something like a collision system.