-
I'm a Rust beginner, and I'm attempting to write a simple 2D collision example in Bevy using a mindset from another language. However, I'm encountering borrowing check violations within nested loops. I'm wondering how to express similar code in Bevy. fn apply_collisions(mut query: Query<(Entity, &mut Ball), With<Ball>>) {
for (entity1, mut ball1) in query.iter_mut() {
for (entity2, mut ball2) in query.iter_mut() {
if entity1 != entity2 {
let diff = ball1.position - ball2.position;
let dist = diff.length();
if dist < ball1.radius + ball2.radius {
let t = diff.normalize();
let delta = ball1.radius + ball2.radius - dist;
ball1.position = ball1.position + t.mul(0.5 * delta);
ball2.position = ball2.position + t.mul(-0.5 * delta);
}
}
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Bevy provides the
Check the following example for some ready-made code: bevy/examples/ecs/iter_combinations.rs Lines 148 to 161 in 1c5c947 |
Beta Was this translation helpful? Give feedback.
Bevy provides the
iter_combinations_mut
method. You should use it.iter_combinations_mut
basically exists for this exact use-case. Otherwise it would be impossible to do what you are doing.Check the following example for some ready-made code:
bevy/examples/ecs/iter_combinations.rs
Lines 148 to 161 in 1c5c947