Add Query::contains (#3090)

# Objective

- Fixes #3089
This commit is contained in:
Gingeh 2022-02-08 03:37:34 +00:00
parent 1468211e2b
commit 2f11c9dca8

View File

@ -2,8 +2,8 @@ use crate::{
component::Component, component::Component,
entity::Entity, entity::Entity,
query::{ query::{
Fetch, FilterFetch, QueryCombinationIter, QueryEntityError, QueryIter, QueryState, Fetch, FilterFetch, NopFetch, QueryCombinationIter, QueryEntityError, QueryIter,
WorldQuery, QueryState, WorldQuery,
}, },
world::{Mut, World}, world::{Mut, World},
}; };
@ -961,6 +961,42 @@ where
self.state self.state
.is_empty(self.world, self.last_change_tick, self.change_tick) .is_empty(self.world, self.last_change_tick, self.change_tick)
} }
/// Returns `true` if the given [`Entity`] matches the query.
///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component)]
/// # struct InRange;
/// #
/// # struct Target {
/// # entity: Entity,
/// # }
/// #
/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
/// if in_range_query.contains(target.entity) {
/// println!("Bam!")
/// }
/// }
/// # targeting_system.system();
/// ```
#[inline]
pub fn contains(&self, entity: Entity) -> bool {
// SAFE: NopFetch does not access any members while &self ensures no one has exclusive access
unsafe {
self.state
.get_unchecked_manual::<NopFetch<Q::State>>(
self.world,
entity,
self.last_change_tick,
self.change_tick,
)
.is_ok()
}
}
} }
/// An error that occurs when retrieving a specific [`Entity`]'s component from a [`Query`] /// An error that occurs when retrieving a specific [`Entity`]'s component from a [`Query`]