I'm looking for a generic way to find the nearest transform to a given one. Say I have a Transform of an entity and a Query<&Transform>. Within the query I want to find the nearest target. I guess it must be a very common operation in games. Is there a common (built in?) way to do this?
Below is my attempt to reinvent the wheel. Excuse my Rust. I'm still learning.
fn nearest<'a, I>(origin: &Transform, candidates: &I) -> Option<Transform>
where
I: IntoIterator<Item = &'a Transform> + Clone ,
{
let mut best_candidate: Option<Transform> = None;
let mut shortest_distance = INFINITY;
for candidate in candidates.clone().into_iter() {
if best_candidate == None {
// Anything is better than nothing
best_candidate = Some(*candidate);
shortest_distance = candidate.translation.distance(origin.translation);
} else {
let distance = candidate.translation.distance(origin.translation);
if distance < shortest_distance {
shortest_distance = distance;
best_candidate = Some(*candidate);
}
}
}
best_candidate
}
And here's how I am trying to use it:
nearest(transform, &targets.iter())
The type of targets is Query<&Transform, With<Target>>.
This gives me:
the trait `Clone` is not implemented for `QueryIter<'_, '_, &bevy::prelude::Transform, bevy::prelude::With<Target>>`
It seems to me that Clone should not be required, but as I said, I'm still green when it comes to borrowing and the like.