Query Entity for single component #4603
-
Im building off "Hands on Rust", which is a book using bracket-lib and Legion, but im porting to use Bevy instead. There is a section to use tooltips where it queries all Entities by positions
.iter(ecs)
.filter(|(_, pos, _)| **pos == map_pos )// (5)
.for_each(|(entity, _, name) | {
let screen_pos = *mouse_pos * 4;// (6)
let display = if let Ok(health) = ecs.entry_ref(*entity)// (7)
.unwrap()
.get_component::<Health>()
{
format!("{} : {} hp", &name.0, health.current)// (8)
} else {// (9)
name.0.clone()
};
draw_batch.print(screen_pos, &display);
}); In my port, im doing the following: pub fn tooltips(
world: &World,
input_state: Res<InputState>,
camera_query: Query<&MainCamera>,
positions: Query<(Entity, &Position, &Naming)>,
) {
let camera = camera_query.single();
let mouse_pos = input_state.mouse;
let offset = Point::new(camera.left_x, camera.top_y);
let map_pos = Position::from(mouse_pos + offset);
let mut draw_batch = DrawBatch::new();
draw_batch.target(2);
for (ent, _, name) in positions.iter().filter(|(_, pos, _)| **pos == map_pos) {
let screen_pos = mouse_pos * 4;
let display = if let Some(health) = world.entity(ent).get::<Health>() {
format!("{} ({}/{})", name.0, health.current, health.max)
} else {
name.0.clone()
};
draw_batch.print(screen_pos, &display);
}
} My question is there a way to check for a component on an entity without requiring the world? Seems odd that I have to pull the entire world to check if an entity has a component |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I'm not in any way an experienced bevy user, so there's a substantial chance my advice will turn out to be wrong. That said, could you add |
Beta Was this translation helpful? Give feedback.
I'm not in any way an experienced bevy user, so there's a substantial chance my advice will turn out to be wrong. That said, could you add
Option<&Health>
to your positions query, per this section of the documentation?