pub struct Query<'world, 'state, D, F = ()>where
D: QueryData,
F: QueryFilter,{ /* private fields */ }
Expand description
System parameter that provides selective access to the Component
data stored in a World
.
Enables access to entity identifiers and components from a system, without the need to directly access the world. Its iterators and getter methods return query items. Each query item is a type containing data relative to an entity.
Query
is a generic data structure that accepts two type parameters:
D
(query data). The type of data contained in the query item. Only entities that match the requested data will generate an item. Must implement theQueryData
trait.F
(query filter). A set of conditions that determines whether query items should be kept or discarded. Must implement theQueryFilter
trait. This type parameter is optional.
§System parameter declaration
A query should always be declared as a system parameter.
This section shows the most common idioms involving the declaration of Query
.
§Component access
A query defined with a reference to a component as the query fetch type parameter can be used to generate items that refer to the data of said component.
// A component can be accessed by shared reference...
query: Query<&ComponentA>
// ... or by mutable reference.
query: Query<&mut ComponentA>
§Query filtering
Setting the query filter type parameter will ensure that each query item satisfies the given condition.
// Just `ComponentA` data will be accessed, but only for entities that also contain
// `ComponentB`.
query: Query<&ComponentA, With<ComponentB>>
§QueryData
or QueryFilter
tuples
Using tuples, each Query
type parameter can contain multiple elements.
In the following example, two components are accessed simultaneously, and the query items are filtered on two conditions.
query: Query<(&ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
§Entity identifier access
The identifier of an entity can be made available inside the query item by including Entity
in the query fetch type parameter.
query: Query<(Entity, &ComponentA)>
§Optional component access
A component can be made optional in a query by wrapping it into an Option
.
In this way, a query item can still be generated even if the queried entity does not contain the wrapped component.
In this case, its corresponding value will be None
.
// Generates items for entities that contain `ComponentA`, and optionally `ComponentB`.
query: Query<(&ComponentA, Option<&ComponentB>)>
See the documentation for AnyOf
to idiomatically declare many optional components.
See the performance section to learn more about the impact of optional components.
§Disjoint queries
A system cannot contain two queries that break Rust’s mutability rules.
In this case, the Without
filter can be used to disjoint them.
In the following example, two queries mutably access the same component.
Executing this system will panic, since an entity could potentially match the two queries at the same time by having both Player
and Enemy
components.
This would violate mutability rules.
fn randomize_health(
player_query: Query<&mut Health, With<Player>>,
enemy_query: Query<&mut Health, With<Enemy>>,
)
Adding a Without
filter will disjoint the queries.
In this way, any entity that has both Player
and Enemy
components is excluded from both queries.
fn randomize_health(
player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
)
An alternative to this idiom is to wrap the conflicting queries into a ParamSet
.
§Whole Entity Access
EntityRef
s can be fetched from a query. This will give read-only access to any component on the entity,
and can be use to dynamically fetch any component without baking it into the query type. Due to this global
access to the entity, this will block any other system from parallelizing with it. As such these queries
should be sparingly used.
query: Query<(EntityRef, &ComponentA)>
As EntityRef
can read any component on an entity, a query using it will conflict with any mutable
access. It is strongly advised to couple EntityRef
queries with the use of either With
/Without
filters or ParamSets
. This also limits the scope of the query, which will improve iteration performance
and also allows it to parallelize with other non-conflicting systems.
// This will panic!
query: Query<(EntityRef, &mut ComponentA)>
// This will not panic.
query_a: Query<EntityRef, With<ComponentA>>,
query_b: Query<&mut ComponentB, Without<ComponentA>>,
§Accessing query items
The following table summarizes the behavior of the safe methods that can be used to get query items.
Query methods | Effect |
---|---|
iter [_mut ] | Returns an iterator over all query items. |
for_each [_mut ],par_iter [_mut ] | Runs a specified function for each query item. |
iter_many [_mut ] | Iterates or runs a specified function over query items generated by a list of entities. |
iter_combinations [_mut ] | Returns an iterator over all combinations of a specified number of query items. |
get [_mut ] | Returns the query item for the specified entity. |
many [_mut ],get_many [_mut ] | Returns the query items for the specified entities. |
single [_mut ],get_single [_mut ] | Returns the query item while verifying that there aren’t others. |
There are two methods for each type of query operation: immutable and mutable (ending with _mut
).
When using immutable methods, the query items returned are of type ROQueryItem
, a read-only version of the query item.
In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
§Performance
Creating a Query
is a low-cost constant operation.
Iterating it, on the other hand, fetches data from the world and generates items, which can have a significant computational cost.
Table
component storage type is much more optimized for query iteration than SparseSet
.
Two systems cannot be executed in parallel if both access the same component type where at least one of the accesses is mutable. This happens unless the executor can verify that no entity could be found in both queries.
Optional components increase the number of entities a query has to match against. This can hurt iteration performance, especially if the query solely consists of only optional components, since the query would iterate over each entity in the world.
The following table compares the computational complexity of the various methods and operations, where:
- n is the number of entities that match the query,
- r is the number of elements in a combination,
- k is the number of involved entities in the operation,
- a is the number of archetypes in the world,
- C is the binomial coefficient, used to count combinations. nCr is read as “n choose r” and is equivalent to the number of distinct unordered subsets of r elements that can be taken from a set of n elements.
Query operation | Computational complexity |
---|---|
iter [_mut ] | O(n) |
for_each [_mut ],par_iter [_mut ] | O(n) |
iter_many [_mut ] | O(k) |
iter_combinations [_mut ] | O(nCr) |
get [_mut ] | O(1) |
(get_ )many | O(k) |
(get_ )many_mut | O(k2) |
single [_mut ],get_single [_mut ] | O(a) |
Archetype based filtering (With , Without , Or ) | O(a) |
Change detection filtering (Added , Changed ) | O(a + n) |
for_each
methods are seen to be generally faster than their iter
version on worlds with high archetype fragmentation.
As iterators are in general more flexible and better integrated with the rest of the Rust ecosystem,
it is advised to use iter
methods over for_each
.
It is strongly advised to only use for_each
if it tangibly improves performance:
be sure profile or benchmark both before and after the change.
Implementations§
source§impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
sourcepub fn to_readonly(&self) -> Query<'_, 's, <D as QueryData>::ReadOnly, F>
pub fn to_readonly(&self) -> Query<'_, 's, <D as QueryData>::ReadOnly, F>
Returns another Query
from this that fetches the read-only version of the query items.
For example, Query<(&mut D1, &D2, &mut D3), With<F>>
will become Query<(&D1, &D2, &D3), With<F>>
.
This can be useful when working around the borrow checker,
or reusing functionality between systems via functions that accept query types.
sourcepub fn iter(&self) -> QueryIter<'_, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter(&self) -> QueryIter<'_, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator
over the read-only query items.
§Example
Here, the report_names_system
iterates over the Player
component of every entity that contains it:
fn report_names_system(query: Query<&Player>) {
for player in &query {
println!("Say hello to {}!", player.name);
}
}
§See also
Examples found in repository?
More examples
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
fn count_entities(all_entities: Query<()>) {
dbg!(all_entities.iter().count());
}
#[derive(Component)]
struct Callback(SystemId);
#[derive(Component)]
struct Triggered;
fn setup(world: &mut World) {
let button_pressed_id = world.register_system(button_pressed);
world.spawn((Callback(button_pressed_id), Triggered));
// This entity does not have a Triggered component, so its callback won't run.
let slider_toggled_id = world.register_system(slider_toggled);
world.spawn(Callback(slider_toggled_id));
world.run_system_once(count_entities);
}
fn button_pressed() {
println!("A button was pressed!");
}
fn slider_toggled() {
println!("A slider was toggled!");
}
/// Runs the systems associated with each `Callback` component if the entity also has a Triggered component.
///
/// This could be done in an exclusive system rather than using `Commands` if preferred.
fn evaluate_callbacks(query: Query<&Callback, With<Triggered>>, mut commands: Commands) {
for callback in query.iter() {
commands.run_system(callback.0);
}
}
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
timer.0.tick(time.delta());
if timer.0.just_finished() {
info!("Lights: {}", lights.iter().len());
}
}
struct LogVisibleLights;
impl Plugin for LogVisibleLights {
fn build(&self, app: &mut App) {
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
}
}
// System for printing the number of meshes on every tick of the timer
fn print_visible_light_count(
time: Res<Time>,
mut timer: Local<PrintingTimer>,
visible: Query<&ExtractedPointLight>,
global_light_meta: Res<GlobalLightMeta>,
) {
timer.0.tick(time.delta());
if timer.0.just_finished() {
info!(
"Visible Lights: {}, Rendered Lights: {}",
visible.iter().len(),
global_light_meta.entity_to_index.len()
);
}
}
40 41 42 43 44 45 46 47 48 49 50 51
fn remove_component(
time: Res<Time>,
mut commands: Commands,
query: Query<Entity, With<MyComponent>>,
) {
// After two seconds have passed the `Component` is removed.
if time.elapsed_seconds() > 2.0 {
if let Some(entity) = query.iter().next() {
commands.entity(entity).remove::<MyComponent>();
}
}
}
- examples/stress_tests/many_cubes.rs
- examples/3d/reflection_probes.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/animated_material.rs
- examples/asset/asset_decompression.rs
- examples/3d/irradiance_volumes.rs
- examples/2d/bounding_2d.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/lightmaps.rs
- examples/math/render_primitives.rs
- examples/ui/size_constraints.rs
sourcepub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> ⓘ
pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> ⓘ
Returns an Iterator
over the query items.
§Example
Here, the gravity_system
updates the Velocity
component of every entity that contains it:
fn gravity_system(mut query: Query<&mut Velocity>) {
const DELTA: f32 = 1.0 / 60.0;
for mut velocity in &mut query {
velocity.y -= 9.8 * DELTA;
}
}
§See also
iter
for read-only query items.for_each_mut
for the closure based alternative.
Examples found in repository?
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
for mut transform in query.iter_mut() {
transform.rotation *= Quat::from_rotation_z(time.delta_seconds() / 5.);
}
}
#[derive(States, Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
enum Test {
AabbSweep,
CircleSweep,
#[default]
RayCast,
AabbCast,
CircleCast,
}
fn update_test_state(
keycode: Res<ButtonInput<KeyCode>>,
cur_state: Res<State<Test>>,
mut state: ResMut<NextState<Test>>,
) {
if !keycode.just_pressed(KeyCode::Space) {
return;
}
use Test::*;
let next = match **cur_state {
AabbSweep => CircleSweep,
CircleSweep => RayCast,
RayCast => AabbCast,
AabbCast => CircleCast,
CircleCast => AabbSweep,
};
state.set(next);
}
fn update_text(mut text: Query<&mut Text>, cur_state: Res<State<Test>>) {
if !cur_state.is_changed() {
return;
}
let mut text = text.single_mut();
let text = &mut text.sections[0].value;
text.clear();
text.push_str("Intersection test:\n");
use Test::*;
for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
let s = if **cur_state == test { "*" } else { " " };
text.push_str(&format!(" {s} {test:?} {s}\n"));
}
text.push_str("\npress Space to cycle");
}
#[derive(Component)]
enum Shape {
Rectangle(Rectangle),
Circle(Circle),
Triangle(Triangle2d),
Line(Segment2d),
Capsule(Capsule2d),
Polygon(RegularPolygon),
}
fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
let color = Color::GRAY;
for (shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
match shape {
Shape::Rectangle(r) => {
gizmos.primitive_2d(*r, translation, rotation, color);
}
Shape::Circle(c) => {
gizmos.primitive_2d(*c, translation, rotation, color);
}
Shape::Triangle(t) => {
gizmos.primitive_2d(*t, translation, rotation, color);
}
Shape::Line(l) => {
gizmos.primitive_2d(*l, translation, rotation, color);
}
Shape::Capsule(c) => {
gizmos.primitive_2d(*c, translation, rotation, color);
}
Shape::Polygon(p) => {
gizmos.primitive_2d(*p, translation, rotation, color);
}
}
}
}
#[derive(Component)]
enum DesiredVolume {
Aabb,
Circle,
}
#[derive(Component, Debug)]
enum CurrentVolume {
Aabb(Aabb2d),
Circle(BoundingCircle),
}
fn update_volumes(
mut commands: Commands,
query: Query<
(Entity, &DesiredVolume, &Shape, &Transform),
Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
>,
) {
for (entity, desired_volume, shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
match desired_volume {
DesiredVolume::Aabb => {
let aabb = match shape {
Shape::Rectangle(r) => r.aabb_2d(translation, rotation),
Shape::Circle(c) => c.aabb_2d(translation, rotation),
Shape::Triangle(t) => t.aabb_2d(translation, rotation),
Shape::Line(l) => l.aabb_2d(translation, rotation),
Shape::Capsule(c) => c.aabb_2d(translation, rotation),
Shape::Polygon(p) => p.aabb_2d(translation, rotation),
};
commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
}
DesiredVolume::Circle => {
let circle = match shape {
Shape::Rectangle(r) => r.bounding_circle(translation, rotation),
Shape::Circle(c) => c.bounding_circle(translation, rotation),
Shape::Triangle(t) => t.bounding_circle(translation, rotation),
Shape::Line(l) => l.bounding_circle(translation, rotation),
Shape::Capsule(c) => c.bounding_circle(translation, rotation),
Shape::Polygon(p) => p.bounding_circle(translation, rotation),
};
commands
.entity(entity)
.insert(CurrentVolume::Circle(circle));
}
}
}
}
fn render_volumes(mut gizmos: Gizmos, query: Query<(&CurrentVolume, &Intersects)>) {
for (volume, intersects) in query.iter() {
let color = if **intersects {
Color::CYAN
} else {
Color::ORANGE_RED
};
match volume {
CurrentVolume::Aabb(a) => {
gizmos.rect_2d(a.center(), 0., a.half_size() * 2., color);
}
CurrentVolume::Circle(c) => {
gizmos.circle_2d(c.center(), c.radius(), color);
}
}
}
}
#[derive(Component, Deref, DerefMut, Default)]
struct Intersects(bool);
const OFFSET_X: f32 = 125.;
const OFFSET_Y: f32 = 75.;
fn setup(mut commands: Commands, loader: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(-OFFSET_X, OFFSET_Y, 0.),
..default()
},
Shape::Circle(Circle::new(45.)),
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(0., OFFSET_Y, 0.),
..default()
},
Shape::Rectangle(Rectangle::new(80., 80.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(OFFSET_X, OFFSET_Y, 0.),
..default()
},
Shape::Triangle(Triangle2d::new(
Vec2::new(-40., -40.),
Vec2::new(-20., 40.),
Vec2::new(40., 50.),
)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(-OFFSET_X, -OFFSET_Y, 0.),
..default()
},
Shape::Line(Segment2d::new(Direction2d::from_xy(1., 0.3).unwrap(), 90.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(0., -OFFSET_Y, 0.),
..default()
},
Shape::Capsule(Capsule2d::new(25., 50.)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
SpatialBundle {
transform: Transform::from_xyz(OFFSET_X, -OFFSET_Y, 0.),
..default()
},
Shape::Polygon(RegularPolygon::new(50., 6)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn(
TextBundle::from_section(
"",
TextStyle {
font: loader.load("fonts/FiraMono-Medium.ttf"),
font_size: 26.0,
..default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::Px(10.0),
left: Val::Px(10.0),
..default()
}),
);
}
fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
gizmos.line_2d(
ray.ray.origin,
ray.ray.origin + *ray.ray.direction * ray.max,
Color::WHITE,
);
for r in [1., 2., 3.] {
gizmos.circle_2d(ray.ray.origin, r, Color::FUCHSIA);
}
}
fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
let ray = Vec2::new(time.elapsed_seconds().cos(), time.elapsed_seconds().sin());
let dist = 150. + (0.5 * time.elapsed_seconds()).sin().abs() * 500.;
let aabb_ray = Ray2d {
origin: ray * 250.,
direction: Direction2d::new_unchecked(-ray),
};
let ray_cast = RayCast2d::from_ray(aabb_ray, dist - 20.);
draw_ray(gizmos, &ray_cast);
ray_cast
}
fn ray_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match volume {
CurrentVolume::Aabb(a) => ray_cast.aabb_intersection_at(a),
CurrentVolume::Circle(c) => ray_cast.circle_intersection_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
for r in [1., 2., 3.] {
gizmos.circle_2d(
ray_cast.ray.origin + *ray_cast.ray.direction * toi,
r,
Color::GREEN,
);
}
}
}
}
fn aabb_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let aabb_cast = AabbCast2d {
aabb: Aabb2d::new(Vec2::ZERO, Vec2::splat(15.)),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(a) => aabb_cast.aabb_collision_at(a),
CurrentVolume::Circle(_) => None,
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.rect_2d(
aabb_cast.ray.ray.origin
+ *aabb_cast.ray.ray.direction * toi
+ aabb_cast.aabb.center(),
0.,
aabb_cast.aabb.half_size() * 2.,
Color::GREEN,
);
}
}
}
fn bounding_circle_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let circle_cast = BoundingCircleCast {
circle: BoundingCircle::new(Vec2::ZERO, 15.),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(_) => None,
CurrentVolume::Circle(c) => circle_cast.circle_collision_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.circle_2d(
circle_cast.ray.ray.origin
+ *circle_cast.ray.ray.direction * toi
+ circle_cast.circle.center(),
circle_cast.circle.radius(),
Color::GREEN,
);
}
}
}
fn get_intersection_position(time: &Time) -> Vec2 {
let x = (0.8 * time.elapsed_seconds()).cos() * 250.;
let y = (0.4 * time.elapsed_seconds()).sin() * 100.;
Vec2::new(x, y)
}
fn aabb_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let aabb = Aabb2d::new(center, Vec2::splat(50.));
gizmos.rect_2d(center, 0., aabb.half_size() * 2., Color::YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => aabb.intersects(a),
CurrentVolume::Circle(c) => aabb.intersects(c),
};
**intersects = hit;
}
}
fn circle_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let circle = BoundingCircle::new(center, 50.);
gizmos.circle_2d(center, circle.radius(), Color::YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => circle.intersects(a),
CurrentVolume::Circle(c) => circle.intersects(c),
};
**intersects = hit;
}
}
More examples
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
fn update_text(
mut text_query: Query<&mut Text>,
app_status: Res<AppStatus>,
asset_server: Res<AssetServer>,
) {
for mut text in text_query.iter_mut() {
*text = app_status.create_text(&asset_server);
}
}
impl AppStatus {
// Constructs the help text at the bottom of the screen based on the
// application status.
fn create_text(&self, asset_server: &AssetServer) -> Text {
let irradiance_volume_help_text = if self.irradiance_volume_present {
DISABLE_IRRADIANCE_VOLUME_HELP_TEXT
} else {
ENABLE_IRRADIANCE_VOLUME_HELP_TEXT
};
let voxels_help_text = if self.voxels_visible {
HIDE_VOXELS_HELP_TEXT
} else {
SHOW_VOXELS_HELP_TEXT
};
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
let switch_mesh_help_text = match self.model {
ExampleModel::Sphere => SWITCH_TO_FOX_HELP_TEXT,
ExampleModel::Fox => SWITCH_TO_SPHERE_HELP_TEXT,
};
Text::from_section(
format!(
"{}\n{}\n{}\n{}\n{}",
CLICK_TO_MOVE_HELP_TEXT,
voxels_help_text,
irradiance_volume_help_text,
rotation_help_text,
switch_mesh_help_text
),
TextStyle {
font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 24.0,
color: Color::ANTIQUE_WHITE,
},
)
}
}
// Rotates the camera a bit every frame.
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
time: Res<Time>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED * time.delta_seconds())
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
// Toggles between the unskinned sphere model and the skinned fox model if the
// user requests it.
fn change_main_object(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut sphere_query: Query<
&mut Visibility,
(With<MainObject>, With<Handle<Mesh>>, Without<Handle<Scene>>),
>,
mut fox_query: Query<&mut Visibility, (With<MainObject>, With<Handle<Scene>>)>,
) {
if !keyboard.just_pressed(KeyCode::Tab) {
return;
}
let Some(mut sphere_visibility) = sphere_query.iter_mut().next() else {
return;
};
let Some(mut fox_visibility) = fox_query.iter_mut().next() else {
return;
};
match app_status.model {
ExampleModel::Sphere => {
*sphere_visibility = Visibility::Hidden;
*fox_visibility = Visibility::Visible;
app_status.model = ExampleModel::Fox;
}
ExampleModel::Fox => {
*sphere_visibility = Visibility::Visible;
*fox_visibility = Visibility::Hidden;
app_status.model = ExampleModel::Sphere;
}
}
}
impl Default for AppStatus {
fn default() -> Self {
Self {
irradiance_volume_present: true,
rotating: true,
model: ExampleModel::Sphere,
voxels_visible: false,
}
}
}
// Turns on and off the irradiance volume as requested by the user.
fn toggle_irradiance_volumes(
mut commands: Commands,
keyboard: Res<ButtonInput<KeyCode>>,
light_probe_query: Query<Entity, With<LightProbe>>,
mut app_status: ResMut<AppStatus>,
assets: Res<ExampleAssets>,
mut ambient_light: ResMut<AmbientLight>,
) {
if !keyboard.just_pressed(KeyCode::Space) {
return;
};
let Some(light_probe) = light_probe_query.iter().next() else {
return;
};
if app_status.irradiance_volume_present {
commands.entity(light_probe).remove::<IrradianceVolume>();
ambient_light.brightness = AMBIENT_LIGHT_BRIGHTNESS * IRRADIANCE_VOLUME_INTENSITY;
app_status.irradiance_volume_present = false;
} else {
commands.entity(light_probe).insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
});
ambient_light.brightness = 0.0;
app_status.irradiance_volume_present = true;
}
}
fn toggle_rotation(keyboard: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>) {
if keyboard.just_pressed(KeyCode::Enter) {
app_status.rotating = !app_status.rotating;
}
}
// Handles clicks on the plane that reposition the object.
fn handle_mouse_clicks(
buttons: Res<ButtonInput<MouseButton>>,
windows: Query<&Window, With<PrimaryWindow>>,
cameras: Query<(&Camera, &GlobalTransform)>,
mut main_objects: Query<&mut Transform, With<MainObject>>,
) {
if !buttons.pressed(MouseButton::Left) {
return;
}
let Some(mouse_position) = windows
.iter()
.next()
.and_then(|window| window.cursor_position())
else {
return;
};
let Some((camera, camera_transform)) = cameras.iter().next() else {
return;
};
// Figure out where the user clicked on the plane.
let Some(ray) = camera.viewport_to_world(camera_transform, mouse_position) else {
return;
};
let Some(ray_distance) = ray.intersect_plane(Vec3::ZERO, Plane3d::new(Vec3::Y)) else {
return;
};
let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance;
// Move all the main objeccts.
for mut transform in main_objects.iter_mut() {
transform.translation = vec3(
plane_intersection.x,
transform.translation.y,
plane_intersection.z,
);
}
}
impl FromWorld for ExampleAssets {
fn from_world(world: &mut World) -> Self {
// Load all the assets.
let asset_server = world.resource::<AssetServer>();
let fox = asset_server.load("models/animated/Fox.glb#Scene0");
let main_scene =
asset_server.load("models/IrradianceVolumeExample/IrradianceVolumeExample.glb#Scene0");
let irradiance_volume = asset_server.load::<Image>("irradiance_volumes/Example.vxgi.ktx2");
let fox_animation =
asset_server.load::<AnimationClip>("models/animated/Fox.glb#Animation1");
// Just use a specular map for the skybox since it's not too blurry.
// In reality you wouldn't do this--you'd use a real skybox texture--but
// reusing the textures like this saves space in the Bevy repository.
let skybox = asset_server.load::<Image>("environment_maps/pisa_specular_rgb9e5_zstd.ktx2");
let mut mesh_assets = world.resource_mut::<Assets<Mesh>>();
let main_sphere = mesh_assets.add(Sphere::default().mesh().uv(32, 18));
let voxel_cube = mesh_assets.add(Cuboid::default());
let mut standard_material_assets = world.resource_mut::<Assets<StandardMaterial>>();
let main_material = standard_material_assets.add(Color::SILVER);
ExampleAssets {
main_sphere,
fox,
main_sphere_material: main_material,
main_scene,
irradiance_volume,
fox_animation,
voxel_cube,
skybox,
}
}
}
// Plays the animation on the fox.
fn play_animations(assets: Res<ExampleAssets>, mut players: Query<&mut AnimationPlayer>) {
for mut player in players.iter_mut() {
// This will safely do nothing if the animation is already playing.
player.play(assets.fox_animation.clone()).repeat();
}
}
fn create_cubes(
image_assets: Res<Assets<Image>>,
mut commands: Commands,
irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
voxel_cubes: Query<Entity, With<VoxelCube>>,
example_assets: Res<ExampleAssets>,
mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
// If voxel cubes have already been spawned, don't do anything.
if !voxel_cubes.is_empty() {
return;
}
let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
return;
};
for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
continue;
};
let resolution = image.texture_descriptor.size;
let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
base: StandardMaterial::from(Color::RED),
extension: VoxelVisualizationExtension {
irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
transform: VOXEL_TRANSFORM.inverse(),
inverse_transform: VOXEL_TRANSFORM,
resolution: uvec3(
resolution.width,
resolution.height,
resolution.depth_or_array_layers,
),
intensity: IRRADIANCE_VOLUME_INTENSITY,
},
},
});
let scale = vec3(
1.0 / resolution.width as f32,
1.0 / resolution.height as f32,
1.0 / resolution.depth_or_array_layers as f32,
);
// Spawn a cube for each voxel.
for z in 0..resolution.depth_or_array_layers {
for y in 0..resolution.height {
for x in 0..resolution.width {
let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
let pos = global_transform.transform_point(uvw);
let voxel_cube = commands
.spawn(MaterialMeshBundle {
mesh: example_assets.voxel_cube.clone(),
material: voxel_cube_material.clone(),
transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
.with_translation(pos),
..default()
})
.insert(VoxelCube)
.insert(NotShadowCaster)
.id();
commands.entity(voxel_cube_parent).add_child(voxel_cube);
}
}
}
}
}
// Draws a gizmo showing the bounds of the irradiance volume.
fn draw_gizmo(
mut gizmos: Gizmos,
irradiance_volume_query: Query<&GlobalTransform, With<IrradianceVolume>>,
app_status: Res<AppStatus>,
) {
if app_status.voxels_visible {
for transform in irradiance_volume_query.iter() {
gizmos.cuboid(*transform, GIZMO_COLOR);
}
}
}
// Handles a request from the user to toggle the voxel visibility on and off.
fn toggle_voxel_visibility(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut voxel_cube_parent_query: Query<&mut Visibility, With<VoxelCubeParent>>,
) {
if !keyboard.just_pressed(KeyCode::Backspace) {
return;
}
app_status.voxels_visible = !app_status.voxels_visible;
for mut visibility in voxel_cube_parent_query.iter_mut() {
*visibility = if app_status.voxels_visible {
Visibility::Visible
} else {
Visibility::Hidden
};
}
}
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
fn update_text(
mut text_query: Query<&mut Text>,
app_status: Res<AppStatus>,
asset_server: Res<AssetServer>,
) {
for mut text in text_query.iter_mut() {
*text = app_status.create_text(&asset_server);
}
}
impl TryFrom<u32> for ReflectionMode {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0 => Ok(ReflectionMode::None),
1 => Ok(ReflectionMode::EnvironmentMap),
2 => Ok(ReflectionMode::ReflectionProbe),
_ => Err(()),
}
}
}
impl Display for ReflectionMode {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
let text = match *self {
ReflectionMode::None => "No reflections",
ReflectionMode::EnvironmentMap => "Environment map",
ReflectionMode::ReflectionProbe => "Reflection probe",
};
formatter.write_str(text)
}
}
impl AppStatus {
// Constructs the help text at the bottom of the screen based on the
// application status.
fn create_text(&self, asset_server: &AssetServer) -> Text {
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
Text::from_section(
format!(
"{}\n{}\n{}",
self.reflection_mode, rotation_help_text, REFLECTION_MODE_HELP_TEXT
),
TextStyle {
font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 24.0,
color: Color::ANTIQUE_WHITE,
},
)
}
}
// Creates the world environment map light, used as a fallback if no reflection
// probe is applicable to a mesh.
fn create_camera_environment_map_light(cubemaps: &Cubemaps) -> EnvironmentMapLight {
EnvironmentMapLight {
diffuse_map: cubemaps.diffuse.clone(),
specular_map: cubemaps.specular_environment_map.clone(),
intensity: 5000.0,
}
}
// Rotates the camera a bit every frame.
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED)
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
- examples/3d/parallax_mapping.rs
- examples/input/text_input.rs
- examples/3d/deferred_rendering.rs
- examples/ui/overflow.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/audio/spatial_audio_2d.rs
- examples/time/virtual_time.rs
- examples/3d/spotlight.rs
- examples/audio/spatial_audio_3d.rs
- examples/ui/viewport_debug.rs
- examples/3d/tonemapping.rs
- examples/math/render_primitives.rs
- examples/ui/display_and_visibility.rs
- examples/stress_tests/many_buttons.rs
- examples/games/alien_cake_addict.rs
- examples/ui/size_constraints.rs
sourcepub fn iter_combinations<const K: usize>(
&self
) -> QueryCombinationIter<'_, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
pub fn iter_combinations<const K: usize>( &self ) -> QueryCombinationIter<'_, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
Returns a QueryCombinationIter
over all combinations of K
read-only query items without repetition.
§Example
fn some_system(query: Query<&ComponentA>) {
for [a1, a2] in query.iter_combinations() {
// ...
}
}
§See also
iter_combinations_mut
for mutable query item combinations.
sourcepub fn iter_combinations_mut<const K: usize>(
&mut self
) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
pub fn iter_combinations_mut<const K: usize>( &mut self ) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
Returns a QueryCombinationIter
over all combinations of K
query items without repetition.
§Example
fn some_system(mut query: Query<&mut ComponentA>) {
let mut combinations = query.iter_combinations_mut();
while let Some([mut a1, mut a2]) = combinations.fetch_next() {
// mutably access components data
}
}
§See also
iter_combinations
for read-only query item combinations.
Examples found in repository?
126 127 128 129 130 131 132 133 134 135 136 137 138 139
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;
}
}
sourcepub fn iter_many<EntityList>(
&self,
entities: EntityList
) -> QueryManyIter<'_, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many<EntityList>( &self, entities: EntityList ) -> QueryManyIter<'_, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator
over the read-only query items generated from an Entity
list.
Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.
§Example
// A component containing an entity list.
#[derive(Component)]
struct Friends {
list: Vec<Entity>,
}
fn system(
friends_query: Query<&Friends>,
counter_query: Query<&Counter>,
) {
for friends in &friends_query {
for counter in counter_query.iter_many(&friends.list) {
println!("Friend's counter: {:?}", counter.value);
}
}
}
§See also
iter_many_mut
to get mutable query items.
sourcepub fn iter_many_mut<EntityList>(
&mut self,
entities: EntityList
) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many_mut<EntityList>( &mut self, entities: EntityList ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an iterator over the query items generated from an Entity
list.
Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.
§Examples
#[derive(Component)]
struct Counter {
value: i32
}
#[derive(Component)]
struct Friends {
list: Vec<Entity>,
}
fn system(
friends_query: Query<&Friends>,
mut counter_query: Query<&mut Counter>,
) {
for friends in &friends_query {
let mut iter = counter_query.iter_many_mut(&friends.list);
while let Some(mut counter) = iter.fetch_next() {
println!("Friend's counter: {:?}", counter.value);
counter.value += 1;
}
}
}
sourcepub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> ⓘ
pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> ⓘ
sourcepub unsafe fn iter_combinations_unsafe<const K: usize>(
&self
) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
pub unsafe fn iter_combinations_unsafe<const K: usize>( &self ) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
Iterates over all possible combinations of K
query items without repetition.
§Safety
This allows aliased mutability. You must make sure this call does not result in multiple mutable references to the same component.
§See also
iter_combinations
anditer_combinations_mut
for the safe versions.
sourcepub unsafe fn iter_many_unsafe<EntityList>(
&self,
entities: EntityList
) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub unsafe fn iter_many_unsafe<EntityList>( &self, entities: EntityList ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator
over the query items generated from an Entity
list.
§Safety
This allows aliased mutability and does not check for entity uniqueness.
You must make sure this call does not result in multiple mutable references to the same component.
Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via Iterator::collect
.
§See also
iter_many_mut
to safely access the query items.
sourcepub fn for_each<'this>(
&'this self,
f: impl FnMut(<<D as QueryData>::ReadOnly as WorldQuery>::Item<'this>)
)
👎Deprecated since 0.13.0: Query::for_each was not idiomatic Rust and has been moved to query.iter().for_each()
pub fn for_each<'this>( &'this self, f: impl FnMut(<<D as QueryData>::ReadOnly as WorldQuery>::Item<'this>) )
Runs f
on each read-only query item.
Shorthand for query.iter().for_each(..)
.
§Example
Here, the report_names_system
iterates over the Player
component of every entity that contains it:
fn report_names_system(query: Query<&Player>) {
query.for_each(|player| {
println!("Say hello to {}!", player.name);
});
}
§See also
for_each_mut
to operate on mutable query items.iter
for the iterator based alternative.
sourcepub fn for_each_mut<'a>(
&'a mut self,
f: impl FnMut(<D as WorldQuery>::Item<'a>)
)
👎Deprecated since 0.13.0: Query::for_each_mut was not idiomatic Rust and has been moved to query.iter_mut().for_each()
pub fn for_each_mut<'a>( &'a mut self, f: impl FnMut(<D as WorldQuery>::Item<'a>) )
Runs f
on each query item.
Shorthand for query.iter_mut().for_each(..)
.
§Example
Here, the gravity_system
updates the Velocity
component of every entity that contains it:
fn gravity_system(mut query: Query<&mut Velocity>) {
const DELTA: f32 = 1.0 / 60.0;
query.for_each_mut(|mut velocity| {
velocity.y -= 9.8 * DELTA;
});
}
§See also
sourcepub fn par_iter(&self) -> QueryParIter<'_, '_, <D as QueryData>::ReadOnly, F>
pub fn par_iter(&self) -> QueryParIter<'_, '_, <D as QueryData>::ReadOnly, F>
Returns a parallel iterator over the query results for the given World
.
This can only be called for read-only queries, see par_iter_mut
for write-queries.
Note that you must use the for_each
method to iterate over the
results, see par_iter_mut
for an example.
sourcepub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F>
pub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F>
Returns a parallel iterator over the query results for the given World
.
This can only be called for mutable queries, see par_iter
for read-only-queries.
§Example
Here, the gravity_system
updates the Velocity
component of every entity that contains it:
fn gravity_system(mut query: Query<&mut Velocity>) {
const DELTA: f32 = 1.0 / 60.0;
query.par_iter_mut().for_each(|mut velocity| {
velocity.y -= 9.8 * DELTA;
});
}
Examples found in repository?
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
fn move_system(mut sprites: Query<(&mut Transform, &Velocity)>) {
// Compute the new location of each sprite in parallel on the
// ComputeTaskPool
//
// This example is only for demonstrative purposes. Using a
// ParallelIterator for an inexpensive operation like addition on only 128
// elements will not typically be faster than just using a normal Iterator.
// See the ParallelIterator documentation for more information on when
// to use or not use ParallelIterator over a normal Iterator.
sprites
.par_iter_mut()
.for_each(|(mut transform, velocity)| {
transform.translation += velocity.extend(0.0);
});
}
// Bounce sprites outside the window
fn bounce_system(windows: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
let window = windows.single();
let width = window.width();
let height = window.height();
let left = width / -2.0;
let right = width / 2.0;
let bottom = height / -2.0;
let top = height / 2.0;
// The default batch size can also be overridden.
// In this case a batch size of 32 is chosen to limit the overhead of
// ParallelIterator, since negating a vector is very inexpensive.
sprites
.par_iter_mut()
.batching_strategy(BatchingStrategy::fixed(32))
.for_each(|(transform, mut v)| {
if !(left < transform.translation.x
&& transform.translation.x < right
&& bottom < transform.translation.y
&& transform.translation.y < top)
{
// For simplicity, just reverse the velocity; don't use realistic bounces
v.0 = -v.0;
}
});
}
sourcepub fn get(
&self,
entity: Entity
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QueryEntityError>
pub fn get( &self, entity: Entity ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QueryEntityError>
Returns the read-only query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
§Example
Here, get
is used to retrieve the exact query item of the entity specified by the SelectedCharacter
resource.
fn print_selected_character_name_system(
query: Query<&Character>,
selection: Res<SelectedCharacter>
)
{
if let Ok(selected_character) = query.get(selection.entity) {
println!("{}", selected_character.name);
}
}
§See also
get_mut
to get a mutable query item.
Examples found in repository?
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
fn mouse_scroll(
mut mouse_wheel_events: EventReader<MouseWheel>,
mut query_list: Query<(&mut ScrollingList, &mut Style, &Parent, &Node)>,
query_node: Query<&Node>,
) {
for mouse_wheel_event in mouse_wheel_events.read() {
for (mut scrolling_list, mut style, parent, list_node) in &mut query_list {
let items_height = list_node.size().y;
let container_height = query_node.get(parent.get()).unwrap().size().y;
let max_scroll = (items_height - container_height).max(0.);
let dy = match mouse_wheel_event.unit {
MouseScrollUnit::Line => mouse_wheel_event.y * 20.,
MouseScrollUnit::Pixel => mouse_wheel_event.y,
};
scrolling_list.position += dy;
scrolling_list.position = scrolling_list.position.clamp(-max_scroll, 0.);
style.top = Val::Px(scrolling_list.position);
}
}
}
More examples
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
fn joint_animation(
time: Res<Time>,
parent_query: Query<&Parent, With<SkinnedMesh>>,
children_query: Query<&Children>,
mut transform_query: Query<&mut Transform>,
) {
// Iter skinned mesh entity
for skinned_mesh_parent in &parent_query {
// Mesh node is the parent of the skinned mesh entity.
let mesh_node_entity = skinned_mesh_parent.get();
// Get `Children` in the mesh node.
let mesh_node_children = children_query.get(mesh_node_entity).unwrap();
// First joint is the second child of the mesh node.
let first_joint_entity = mesh_node_children[1];
// Get `Children` in the first joint.
let first_joint_children = children_query.get(first_joint_entity).unwrap();
// Second joint is the first child of the first joint.
let second_joint_entity = first_joint_children[0];
// Get `Transform` in the second joint.
let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();
second_joint_transform.rotation =
Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
}
}
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
fn set_camera_viewports(
windows: Query<&Window>,
mut resize_events: EventReader<WindowResized>,
mut left_camera: Query<&mut Camera, (With<LeftCamera>, Without<RightCamera>)>,
mut right_camera: Query<&mut Camera, With<RightCamera>>,
) {
// We need to dynamically resize the camera's viewports whenever the window size changes
// so then each camera always takes up half the screen.
// A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
for resize_event in resize_events.read() {
let window = windows.get(resize_event.window).unwrap();
let mut left_camera = left_camera.single_mut();
left_camera.viewport = Some(Viewport {
physical_position: UVec2::new(0, 0),
physical_size: UVec2::new(
window.resolution.physical_width() / 2,
window.resolution.physical_height(),
),
..default()
});
let mut right_camera = right_camera.single_mut();
right_camera.viewport = Some(Viewport {
physical_position: UVec2::new(window.resolution.physical_width() / 2, 0),
physical_size: UVec2::new(
window.resolution.physical_width() / 2,
window.resolution.physical_height(),
),
..default()
});
}
}
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
fn focus_camera(
time: Res<Time>,
mut game: ResMut<Game>,
mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
) {
const SPEED: f32 = 2.0;
// if there is both a player and a bonus, target the mid-point of them
if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
let transform_query = transforms.p1();
if let (Ok(player_transform), Ok(bonus_transform)) = (
transform_query.get(player_entity),
transform_query.get(bonus_entity),
) {
game.camera_should_focus = player_transform
.translation
.lerp(bonus_transform.translation, 0.5);
}
// otherwise, if there is only a player, target the player
} else if let Some(player_entity) = game.player.entity {
if let Ok(player_transform) = transforms.p1().get(player_entity) {
game.camera_should_focus = player_transform.translation;
}
// otherwise, target the middle
} else {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
}
// calculate the camera motion based on the difference between where the camera is looking
// and where it should be looking; the greater the distance, the faster the motion;
// smooth out the camera movement using the frame time
let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
if camera_motion.length() > 0.2 {
camera_motion *= SPEED * time.delta_seconds();
// set the new camera's actual focus
game.camera_is_focus += camera_motion;
}
// look at that new camera's actual focus
for mut transform in transforms.p0().iter_mut() {
*transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
}
}
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
fn example_control_system(
mut materials: ResMut<Assets<StandardMaterial>>,
controllable: Query<(&Handle<StandardMaterial>, &ExampleControls)>,
mut camera: Query<(&mut Camera, &mut Transform, &GlobalTransform), With<Camera3d>>,
mut labels: Query<(&mut Style, &ExampleLabel)>,
mut display: Query<&mut Text, With<ExampleDisplay>>,
labelled: Query<&GlobalTransform>,
mut state: Local<ExampleState>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.pressed(KeyCode::ArrowUp) {
state.alpha = (state.alpha + time.delta_seconds()).min(1.0);
} else if input.pressed(KeyCode::ArrowDown) {
state.alpha = (state.alpha - time.delta_seconds()).max(0.0);
}
if input.just_pressed(KeyCode::Space) {
state.unlit = !state.unlit;
}
let randomize_colors = input.just_pressed(KeyCode::KeyC);
for (material_handle, controls) in &controllable {
let material = materials.get_mut(material_handle).unwrap();
material.base_color.set_a(state.alpha);
if controls.color && randomize_colors {
material.base_color.set_r(random());
material.base_color.set_g(random());
material.base_color.set_b(random());
}
if controls.unlit {
material.unlit = state.unlit;
}
}
let (mut camera, mut camera_transform, camera_global_transform) = camera.single_mut();
if input.just_pressed(KeyCode::KeyH) {
camera.hdr = !camera.hdr;
}
let rotation = if input.pressed(KeyCode::ArrowLeft) {
time.delta_seconds()
} else if input.pressed(KeyCode::ArrowRight) {
-time.delta_seconds()
} else {
0.0
};
camera_transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(rotation));
for (mut style, label) in &mut labels {
let world_position = labelled.get(label.entity).unwrap().translation() + Vec3::Y;
let viewport_position = camera
.world_to_viewport(camera_global_transform, world_position)
.unwrap();
style.top = Val::Px(viewport_position.y);
style.left = Val::Px(viewport_position.x);
}
let mut display = display.single_mut();
display.sections[0].value = format!(
" HDR: {}\nAlpha: {:.2}",
if camera.hdr { "ON " } else { "OFF" },
state.alpha
);
}
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
fn update_buttons(
mut button_query: Query<
(Entity, &Interaction, &Constraint, &ButtonValue),
Changed<Interaction>,
>,
mut bar_query: Query<&mut Style, With<Bar>>,
mut text_query: Query<&mut Text>,
children_query: Query<&Children>,
mut button_activated_event: EventWriter<ButtonActivatedEvent>,
) {
let mut style = bar_query.single_mut();
for (button_id, interaction, constraint, value) in button_query.iter_mut() {
match interaction {
Interaction::Pressed => {
button_activated_event.send(ButtonActivatedEvent(button_id));
match constraint {
Constraint::FlexBasis => {
style.flex_basis = value.0;
}
Constraint::Width => {
style.width = value.0;
}
Constraint::MinWidth => {
style.min_width = value.0;
}
Constraint::MaxWidth => {
style.max_width = value.0;
}
}
}
Interaction::Hovered => {
if let Ok(children) = children_query.get(button_id) {
for &child in children {
if let Ok(grand_children) = children_query.get(child) {
for &grandchild in grand_children {
if let Ok(mut text) = text_query.get_mut(grandchild) {
if text.sections[0].style.color != ACTIVE_TEXT_COLOR {
text.sections[0].style.color = HOVERED_TEXT_COLOR;
}
}
}
}
}
}
}
Interaction::None => {
if let Ok(children) = children_query.get(button_id) {
for &child in children {
if let Ok(grand_children) = children_query.get(child) {
for &grandchild in grand_children {
if let Ok(mut text) = text_query.get_mut(grandchild) {
if text.sections[0].style.color != ACTIVE_TEXT_COLOR {
text.sections[0].style.color = UNHOVERED_TEXT_COLOR;
}
}
}
}
}
}
}
}
}
}
fn update_radio_buttons_colors(
mut event_reader: EventReader<ButtonActivatedEvent>,
button_query: Query<(Entity, &Constraint, &Interaction)>,
mut color_query: Query<&mut BackgroundColor>,
mut text_query: Query<&mut Text>,
children_query: Query<&Children>,
) {
for &ButtonActivatedEvent(button_id) in event_reader.read() {
let (_, target_constraint, _) = button_query.get(button_id).unwrap();
for (id, constraint, interaction) in button_query.iter() {
if target_constraint == constraint {
let (border_color, inner_color, text_color) = if id == button_id {
(ACTIVE_BORDER_COLOR, ACTIVE_INNER_COLOR, ACTIVE_TEXT_COLOR)
} else {
(
INACTIVE_BORDER_COLOR,
INACTIVE_INNER_COLOR,
if matches!(interaction, Interaction::Hovered) {
HOVERED_TEXT_COLOR
} else {
UNHOVERED_TEXT_COLOR
},
)
};
color_query.get_mut(id).unwrap().0 = border_color;
if let Ok(children) = children_query.get(id) {
for &child in children {
color_query.get_mut(child).unwrap().0 = inner_color;
if let Ok(grand_children) = children_query.get(child) {
for &grandchild in grand_children {
if let Ok(mut text) = text_query.get_mut(grandchild) {
text.sections[0].style.color = text_color;
}
}
}
}
}
}
}
}
}
sourcepub fn get_many<const N: usize>(
&self,
entities: [Entity; N]
) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N], QueryEntityError>
pub fn get_many<const N: usize>( &self, entities: [Entity; N] ) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N], QueryEntityError>
Returns the read-only query items for the given array of Entity
.
The returned query items are in the same order as the input.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
The elements of the array do not need to be unique, unlike get_many_mut
.
§See also
get_many_mut
to get mutable query items.many
for the panicking version.
sourcepub fn many<const N: usize>(
&self,
entities: [Entity; N]
) -> [<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N]
pub fn many<const N: usize>( &self, entities: [Entity; N] ) -> [<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N]
Returns the read-only query items for the given array of Entity
.
§Panics
This method panics if there is a query mismatch or a non-existing entity.
§Examples
use bevy_ecs::prelude::*;
#[derive(Component)]
struct Targets([Entity; 3]);
#[derive(Component)]
struct Position{
x: i8,
y: i8
};
impl Position {
fn distance(&self, other: &Position) -> i8 {
// Manhattan distance is way easier to compute!
(self.x - other.x).abs() + (self.y - other.y).abs()
}
}
fn check_all_targets_in_range(targeting_query: Query<(Entity, &Targets, &Position)>, targets_query: Query<&Position>){
for (targeting_entity, targets, origin) in &targeting_query {
// We can use "destructuring" to unpack the results nicely
let [target_1, target_2, target_3] = targets_query.many(targets.0);
assert!(target_1.distance(origin) <= 5);
assert!(target_2.distance(origin) <= 5);
assert!(target_3.distance(origin) <= 5);
}
}
§See also
get_many
for the non-panicking version.
sourcepub fn get_mut(
&mut self,
entity: Entity
) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>
pub fn get_mut( &mut self, entity: Entity ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>
Returns the query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
§Example
Here, get_mut
is used to retrieve the exact query item of the entity specified by the PoisonedCharacter
resource.
fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
if let Ok(mut health) = query.get_mut(poisoned.character_id) {
health.0 -= 1;
}
}
§See also
get
to get a read-only query item.
Examples found in repository?
More examples
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
fn move_scene_entities(
time: Res<Time>,
moved_scene: Query<Entity, With<MovedScene>>,
children: Query<&Children>,
mut transforms: Query<&mut Transform>,
) {
for moved_scene_entity in &moved_scene {
let mut offset = 0.;
for entity in children.iter_descendants(moved_scene_entity) {
if let Ok(mut transform) = transforms.get_mut(entity) {
transform.translation = Vec3::new(
offset * time.elapsed_seconds().sin() / 20.,
0.,
time.elapsed_seconds().cos() / 20.,
);
offset += 0.5;
}
}
}
}
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
fn button_system(
mut interaction_query: Query<(&Interaction, &Children), (Changed<Interaction>, With<Button>)>,
mut text_query: Query<&mut Text>,
) {
for (interaction, children) in &mut interaction_query {
let mut text = text_query.get_mut(children[0]).unwrap();
match *interaction {
Interaction::Pressed => {
text.sections[0].value = "Press".to_string();
}
Interaction::Hovered => {
text.sections[0].value = "Hover".to_string();
}
Interaction::None => {
text.sections[0].value = "Button".to_string();
}
}
}
}
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
fn button_system(
interaction_query: Query<
(&Interaction, &TargetCamera, &RotateCamera),
(Changed<Interaction>, With<Button>),
>,
mut camera_query: Query<&mut Transform, With<Camera>>,
) {
for (interaction, target_camera, RotateCamera(direction)) in &interaction_query {
if let Interaction::Pressed = *interaction {
// Since TargetCamera propagates to the children, we can use it to find
// which side of the screen the button is on.
if let Ok(mut camera_transform) = camera_query.get_mut(target_camera.entity()) {
let angle = match direction {
Direction::Left => -0.1,
Direction::Right => 0.1,
};
camera_transform.rotate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, angle));
}
}
}
}
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
fn buttons_handler<T>(
mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
mut text_query: Query<&mut Text>,
) where
T: Send + Sync,
Target<T>: TargetUpdate + Component,
{
for (target, interaction, children) in visibility_button_query.iter_mut() {
if matches!(interaction, Interaction::Pressed) {
let mut target_value = left_panel_query.get_mut(target.id).unwrap();
for &child in children {
if let Ok(mut text) = text_query.get_mut(child) {
text.sections[0].value = target.update_target(target_value.as_mut());
text.sections[0].style.color = if text.sections[0].value.contains("None")
|| text.sections[0].value.contains("Hidden")
{
Color::rgb(1.0, 0.7, 0.7)
} else {
Color::WHITE
};
}
}
}
}
}
fn text_hover(
mut button_query: Query<(&Interaction, &mut BackgroundColor, &Children), Changed<Interaction>>,
mut text_query: Query<&mut Text>,
) {
for (interaction, mut background_color, children) in button_query.iter_mut() {
match interaction {
Interaction::Hovered => {
*background_color = BackgroundColor(Color::BLACK.with_a(0.6));
for &child in children {
if let Ok(mut text) = text_query.get_mut(child) {
// Bypass change detection to avoid recomputation of the text when only changing the color
text.bypass_change_detection().sections[0].style.color = Color::YELLOW;
}
}
}
_ => {
*background_color = BackgroundColor(Color::BLACK.with_a(0.5));
for &child in children {
if let Ok(mut text) = text_query.get_mut(child) {
text.bypass_change_detection().sections[0].style.color =
if text.sections[0].value.contains("None")
|| text.sections[0].value.contains("Hidden")
{
HIDDEN_COLOR
} else {
Color::WHITE
};
}
}
}
}
}
}
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
fn button_system(
mut interaction_query: Query<
(
&Interaction,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
(Changed<Interaction>, With<Button>),
>,
mut text_query: Query<&mut Text>,
) {
for (interaction, mut color, mut border_color, children) in &mut interaction_query {
let mut text = text_query.get_mut(children[0]).unwrap();
match *interaction {
Interaction::Pressed => {
text.sections[0].value = "Press".to_string();
*color = PRESSED_BUTTON.into();
border_color.0 = Color::RED;
}
Interaction::Hovered => {
text.sections[0].value = "Hover".to_string();
*color = HOVERED_BUTTON.into();
border_color.0 = Color::WHITE;
}
Interaction::None => {
text.sections[0].value = "Button".to_string();
*color = NORMAL_BUTTON.into();
border_color.0 = Color::BLACK;
}
}
}
}
sourcepub fn get_many_mut<const N: usize>(
&mut self,
entities: [Entity; N]
) -> Result<[<D as WorldQuery>::Item<'_>; N], QueryEntityError>
pub fn get_many_mut<const N: usize>( &mut self, entities: [Entity; N] ) -> Result<[<D as WorldQuery>::Item<'_>; N], QueryEntityError>
Returns the query items for the given array of Entity
.
The returned query items are in the same order as the input.
In case of a nonexisting entity, duplicate entities or mismatched component, a QueryEntityError
is returned instead.
§See also
sourcepub fn many_mut<const N: usize>(
&mut self,
entities: [Entity; N]
) -> [<D as WorldQuery>::Item<'_>; N]
pub fn many_mut<const N: usize>( &mut self, entities: [Entity; N] ) -> [<D as WorldQuery>::Item<'_>; N]
Returns the query items for the given array of Entity
.
§Panics
This method panics if there is a query mismatch, a non-existing entity, or the same Entity
is included more than once in the array.
§Examples
use bevy_ecs::prelude::*;
#[derive(Component)]
struct Spring{
connected_entities: [Entity; 2],
strength: f32,
}
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
#[derive(Component)]
struct Force {
x: f32,
y: f32,
}
fn spring_forces(spring_query: Query<&Spring>, mut mass_query: Query<(&Position, &mut Force)>){
for spring in &spring_query {
// We can use "destructuring" to unpack our query items nicely
let [(position_1, mut force_1), (position_2, mut force_2)] = mass_query.many_mut(spring.connected_entities);
force_1.x += spring.strength * (position_1.x - position_2.x);
force_1.y += spring.strength * (position_1.y - position_2.y);
// Silence borrow-checker: I have split your mutable borrow!
force_2.x += spring.strength * (position_2.x - position_1.x);
force_2.y += spring.strength * (position_2.y - position_1.y);
}
}
§See also
get_many_mut
for the non panicking version.many
to get read-only query items.
sourcepub unsafe fn get_unchecked(
&self,
entity: Entity
) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>
pub unsafe fn get_unchecked( &self, entity: Entity ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>
Returns the query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
§Safety
This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.
§See also
get_mut
for the safe version.
sourcepub fn get_component<T>(
&self,
entity: Entity
) -> Result<&T, QueryComponentError>where
T: Component,
👎Deprecated since 0.13.0: Please use get
and select for the exact component based on the structure of the exact query as required.
pub fn get_component<T>(
&self,
entity: Entity
) -> Result<&T, QueryComponentError>where
T: Component,
get
and select for the exact component based on the structure of the exact query as required.Returns a shared reference to the component T
of the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
§Example
Here, get_component
is used to retrieve the Character
component of the entity specified by the SelectedCharacter
resource.
fn print_selected_character_name_system(
query: Query<&Character>,
selection: Res<SelectedCharacter>
)
{
if let Ok(selected_character) = query.get_component::<Character>(selection.entity) {
println!("{}", selected_character.name);
}
}
§See also
component
a panicking version of this function.get_component_mut
to get a mutable reference of a component.
sourcepub fn get_component_mut<T>(
&mut self,
entity: Entity
) -> Result<Mut<'_, T>, QueryComponentError>where
T: Component,
👎Deprecated since 0.13.0: Please use get_mut
and select for the exact component based on the structure of the exact query as required.
pub fn get_component_mut<T>(
&mut self,
entity: Entity
) -> Result<Mut<'_, T>, QueryComponentError>where
T: Component,
get_mut
and select for the exact component based on the structure of the exact query as required.Returns a mutable reference to the component T
of the given entity.
In case of a nonexisting entity, mismatched component or missing write access, a QueryComponentError
is returned instead.
§Example
Here, get_component_mut
is used to retrieve the Health
component of the entity specified by the PoisonedCharacter
resource.
fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
if let Ok(mut health) = query.get_component_mut::<Health>(poisoned.character_id) {
health.0 -= 1;
}
}
§See also
component_mut
a panicking version of this function.get_component
to get a shared reference of a component.
sourcepub fn component<T>(&self, entity: Entity) -> &Twhere
T: Component,
👎Deprecated since 0.13.0: Please use get
and select for the exact component based on the structure of the exact query as required.
pub fn component<T>(&self, entity: Entity) -> &Twhere
T: Component,
get
and select for the exact component based on the structure of the exact query as required.Returns a shared reference to the component T
of the given Entity
.
§Panics
Panics in case of a nonexisting entity or mismatched component.
§See also
get_component
a non-panicking version of this function.component_mut
to get a mutable reference of a component.
sourcepub fn component_mut<T>(&mut self, entity: Entity) -> Mut<'_, T>where
T: Component,
👎Deprecated since 0.13.0: Please use get_mut
and select for the exact component based on the structure of the exact query as required.
pub fn component_mut<T>(&mut self, entity: Entity) -> Mut<'_, T>where
T: Component,
get_mut
and select for the exact component based on the structure of the exact query as required.Returns a mutable reference to the component T
of the given entity.
§Panics
Panics in case of a nonexisting entity, mismatched component or missing write access.
§See also
get_component_mut
a non-panicking version of this function.component
to get a shared reference of a component.
sourcepub unsafe fn get_component_unchecked_mut<T>(
&self,
entity: Entity
) -> Result<Mut<'_, T>, QueryComponentError>where
T: Component,
👎Deprecated since 0.13.0: Please use get_unchecked
and select for the exact component based on the structure of the exact query as required.
pub unsafe fn get_component_unchecked_mut<T>(
&self,
entity: Entity
) -> Result<Mut<'_, T>, QueryComponentError>where
T: Component,
get_unchecked
and select for the exact component based on the structure of the exact query as required.Returns a mutable reference to the component T
of the given entity.
In case of a nonexisting entity or mismatched component, a QueryComponentError
is returned instead.
§Safety
This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.
§See also
get_component_mut
for the safe version.
sourcepub fn single(&self) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>
pub fn single(&self) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>
Returns a single read-only query item when there is exactly one entity matching the query.
§Panics
This method panics if the number of query items is not exactly one.
§Example
fn player_system(query: Query<&Position, With<Player>>) {
let player_position = query.single();
// do something with player_position
}
§See also
get_single
for the non-panicking version.single_mut
to get the mutable query item.
Examples found in repository?
154 155 156 157 158 159 160 161 162 163 164 165
fn look_at_star(
mut camera: Query<&mut Transform, (With<Camera>, Without<Star>)>,
star: Query<&Transform, With<Star>>,
) {
let mut camera = camera.single_mut();
let star = star.single();
let new_rotation = camera
.looking_at(star.translation, Vec3::Y)
.rotation
.lerp(camera.rotation, 0.1);
camera.rotation = new_rotation;
}
More examples
15 16 17 18 19 20 21 22 23 24 25 26 27 28
fn screenshot_on_spacebar(
input: Res<ButtonInput<KeyCode>>,
main_window: Query<Entity, With<PrimaryWindow>>,
mut screenshot_manager: ResMut<ScreenshotManager>,
mut counter: Local<u32>,
) {
if input.just_pressed(KeyCode::Space) {
let path = format!("./screenshot-{}.png", *counter);
*counter += 1;
screenshot_manager
.save_screenshot_to_disk(main_window.single(), path)
.unwrap();
}
}
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
fn draw_cursor(
camera_query: Query<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
mut gizmos: Gizmos,
) {
let (camera, camera_transform) = camera_query.single();
let Some(cursor_position) = windows.single().cursor_position() else {
return;
};
// Calculate a world position based on the cursor's position.
let Some(point) = camera.viewport_to_world_2d(camera_transform, cursor_position) else {
return;
};
gizmos.circle_2d(point, 10., Color::WHITE);
}
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
fn scheduled_spawner(
mut commands: Commands,
args: Res<Args>,
windows: Query<&Window>,
mut scheduled: ResMut<BirdScheduled>,
mut counter: ResMut<BevyCounter>,
bird_resources: ResMut<BirdResources>,
) {
let window = windows.single();
if scheduled.waves > 0 {
let bird_resources = bird_resources.into_inner();
spawn_birds(
&mut commands,
args.into_inner(),
&window.resolution,
&mut counter,
scheduled.per_wave,
bird_resources,
None,
scheduled.waves - 1,
);
scheduled.waves -= 1;
}
}
#[derive(Resource)]
struct BirdResources {
textures: Vec<Handle<Image>>,
materials: Vec<Handle<ColorMaterial>>,
quad: Mesh2dHandle,
color_rng: StdRng,
material_rng: StdRng,
velocity_rng: StdRng,
transform_rng: StdRng,
}
#[derive(Component)]
struct StatsText;
#[allow(clippy::too_many_arguments)]
fn setup(
mut commands: Commands,
args: Res<Args>,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
material_assets: ResMut<Assets<ColorMaterial>>,
images: ResMut<Assets<Image>>,
windows: Query<&Window>,
counter: ResMut<BevyCounter>,
) {
warn!(include_str!("warning_string.txt"));
let args = args.into_inner();
let images = images.into_inner();
let mut textures = Vec::with_capacity(args.material_texture_count.max(1));
if matches!(args.mode, Mode::Sprite) || args.material_texture_count > 0 {
textures.push(asset_server.load("branding/icon.png"));
}
init_textures(&mut textures, args, images);
let material_assets = material_assets.into_inner();
let materials = init_materials(args, &textures, material_assets);
let mut bird_resources = BirdResources {
textures,
materials,
quad: meshes
.add(Rectangle::from_size(Vec2::splat(BIRD_TEXTURE_SIZE as f32)))
.into(),
color_rng: StdRng::seed_from_u64(42),
material_rng: StdRng::seed_from_u64(42),
velocity_rng: StdRng::seed_from_u64(42),
transform_rng: StdRng::seed_from_u64(42),
};
let text_section = move |color, value: &str| {
TextSection::new(
value,
TextStyle {
font_size: 40.0,
color,
..default()
},
)
};
commands.spawn(Camera2dBundle::default());
commands
.spawn(NodeBundle {
style: Style {
position_type: PositionType::Absolute,
padding: UiRect::all(Val::Px(5.0)),
..default()
},
z_index: ZIndex::Global(i32::MAX),
background_color: Color::BLACK.with_a(0.75).into(),
..default()
})
.with_children(|c| {
c.spawn((
TextBundle::from_sections([
text_section(Color::GREEN, "Bird Count: "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (raw): "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (SMA): "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (EMA): "),
text_section(Color::CYAN, ""),
]),
StatsText,
));
});
let mut scheduled = BirdScheduled {
per_wave: args.per_wave,
waves: args.waves,
};
if args.benchmark {
let counter = counter.into_inner();
for wave in (0..scheduled.waves).rev() {
spawn_birds(
&mut commands,
args,
&windows.single().resolution,
counter,
scheduled.per_wave,
&mut bird_resources,
Some(wave),
wave,
);
}
scheduled.waves = 0;
}
commands.insert_resource(bird_resources);
commands.insert_resource(scheduled);
}
#[allow(clippy::too_many_arguments)]
fn mouse_handler(
mut commands: Commands,
args: Res<Args>,
time: Res<Time>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
windows: Query<&Window>,
bird_resources: ResMut<BirdResources>,
mut counter: ResMut<BevyCounter>,
mut rng: Local<Option<StdRng>>,
mut wave: Local<usize>,
) {
if rng.is_none() {
*rng = Some(StdRng::seed_from_u64(42));
}
let rng = rng.as_mut().unwrap();
let window = windows.single();
if mouse_button_input.just_released(MouseButton::Left) {
counter.color = Color::rgb_linear(rng.gen(), rng.gen(), rng.gen());
}
if mouse_button_input.pressed(MouseButton::Left) {
let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_seconds_f64()) as usize;
spawn_birds(
&mut commands,
args.into_inner(),
&window.resolution,
&mut counter,
spawn_count,
bird_resources.into_inner(),
None,
*wave,
);
*wave += 1;
}
}
fn bird_velocity_transform(
half_extents: Vec2,
mut translation: Vec3,
velocity_rng: &mut StdRng,
waves: Option<usize>,
dt: f32,
) -> (Transform, Vec3) {
let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);
if let Some(waves) = waves {
// Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
// and with dt-spaced frames of simulation
for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
step_movement(&mut translation, &mut velocity, dt);
handle_collision(half_extents, &translation, &mut velocity);
}
}
(
Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
velocity,
)
}
const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;
#[allow(clippy::too_many_arguments)]
fn spawn_birds(
commands: &mut Commands,
args: &Args,
primary_window_resolution: &WindowResolution,
counter: &mut BevyCounter,
spawn_count: usize,
bird_resources: &mut BirdResources,
waves_to_simulate: Option<usize>,
wave: usize,
) {
let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;
let half_extents = 0.5
* Vec2::new(
primary_window_resolution.width(),
primary_window_resolution.height(),
);
let color = counter.color;
let current_count = counter.count;
match args.mode {
Mode::Sprite => {
let batch = (0..spawn_count)
.map(|count| {
let bird_z = if args.ordered_z {
(current_count + count) as f32 * 0.00001
} else {
bird_resources.transform_rng.gen::<f32>()
};
let (transform, velocity) = bird_velocity_transform(
half_extents,
Vec3::new(bird_x, bird_y, bird_z),
&mut bird_resources.velocity_rng,
waves_to_simulate,
FIXED_DELTA_TIME,
);
let color = if args.vary_per_instance {
Color::rgb_linear(
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
)
} else {
color
};
(
SpriteBundle {
texture: bird_resources
.textures
.choose(&mut bird_resources.material_rng)
.unwrap()
.clone(),
transform,
sprite: Sprite { color, ..default() },
..default()
},
Bird { velocity },
)
})
.collect::<Vec<_>>();
commands.spawn_batch(batch);
}
Mode::Mesh2d => {
let batch = (0..spawn_count)
.map(|count| {
let bird_z = if args.ordered_z {
(current_count + count) as f32 * 0.00001
} else {
bird_resources.transform_rng.gen::<f32>()
};
let (transform, velocity) = bird_velocity_transform(
half_extents,
Vec3::new(bird_x, bird_y, bird_z),
&mut bird_resources.velocity_rng,
waves_to_simulate,
FIXED_DELTA_TIME,
);
let material =
if args.vary_per_instance || args.material_texture_count > args.waves {
bird_resources
.materials
.choose(&mut bird_resources.material_rng)
.unwrap()
.clone()
} else {
bird_resources.materials[wave % bird_resources.materials.len()].clone()
};
(
MaterialMesh2dBundle {
mesh: bird_resources.quad.clone(),
material,
transform,
..default()
},
Bird { velocity },
)
})
.collect::<Vec<_>>();
commands.spawn_batch(batch);
}
}
counter.count += spawn_count;
counter.color = Color::rgb_linear(
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
bird_resources.color_rng.gen(),
);
}
fn step_movement(translation: &mut Vec3, velocity: &mut Vec3, dt: f32) {
translation.x += velocity.x * dt;
translation.y += velocity.y * dt;
velocity.y += GRAVITY * dt;
}
fn movement_system(
args: Res<Args>,
time: Res<Time>,
mut bird_query: Query<(&mut Bird, &mut Transform)>,
) {
let dt = if args.benchmark {
FIXED_DELTA_TIME
} else {
time.delta_seconds()
};
for (mut bird, mut transform) in &mut bird_query {
step_movement(&mut transform.translation, &mut bird.velocity, dt);
}
}
fn handle_collision(half_extents: Vec2, translation: &Vec3, velocity: &mut Vec3) {
if (velocity.x > 0. && translation.x + HALF_BIRD_SIZE > half_extents.x)
|| (velocity.x <= 0. && translation.x - HALF_BIRD_SIZE < -half_extents.x)
{
velocity.x = -velocity.x;
}
let velocity_y = velocity.y;
if velocity_y < 0. && translation.y - HALF_BIRD_SIZE < -half_extents.y {
velocity.y = -velocity_y;
}
if translation.y + HALF_BIRD_SIZE > half_extents.y && velocity_y > 0.0 {
velocity.y = 0.0;
}
}
fn collision_system(windows: Query<&Window>, mut bird_query: Query<(&mut Bird, &Transform)>) {
let window = windows.single();
let half_extents = 0.5 * Vec2::new(window.width(), window.height());
for (mut bird, transform) in &mut bird_query {
handle_collision(half_extents, &transform.translation, &mut bird.velocity);
}
}
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
fn relative_cursor_position_system(
relative_cursor_position_query: Query<&RelativeCursorPosition>,
mut output_query: Query<&mut Text>,
) {
let relative_cursor_position = relative_cursor_position_query.single();
let mut output = output_query.single_mut();
output.sections[0].value =
if let Some(relative_cursor_position) = relative_cursor_position.normalized {
format!(
"({:.1}, {:.1})",
relative_cursor_position.x, relative_cursor_position.y
)
} else {
"unknown".to_string()
};
output.sections[0].style.color = if relative_cursor_position.mouse_over() {
Color::rgb(0.1, 0.9, 0.1)
} else {
Color::rgb(0.9, 0.1, 0.1)
};
}
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
fn listen_keyboard_input_events(
mut commands: Commands,
mut events: EventReader<KeyboardInput>,
mut edit_text: Query<(Entity, &mut Text), (Without<Node>, Without<Bubble>)>,
) {
for event in events.read() {
match event.key_code {
KeyCode::Enter => {
let (entity, text) = edit_text.single();
commands.entity(entity).insert(Bubble {
timer: Timer::from_seconds(5.0, TimerMode::Once),
});
commands.spawn(Text2dBundle {
text: Text::from_section("".to_string(), text.sections[0].style.clone()),
..default()
});
}
KeyCode::Backspace => {
edit_text.single_mut().1.sections[0].value.pop();
}
_ => continue,
}
}
}
sourcepub fn get_single(
&self
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QuerySingleError>
pub fn get_single( &self ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QuerySingleError>
Returns a single read-only query item when there is exactly one entity matching the query.
If the number of query items is not exactly one, a QuerySingleError
is returned instead.
§Example
fn player_scoring_system(query: Query<&PlayerScore>) {
match query.get_single() {
Ok(PlayerScore(score)) => {
println!("Score: {}", score);
}
Err(QuerySingleError::NoEntities(_)) => {
println!("Error: There is no player!");
}
Err(QuerySingleError::MultipleEntities(_)) => {
println!("Error: There is more than one player!");
}
}
}
§See also
get_single_mut
to get the mutable query item.single
for the panicking version.
Examples found in repository?
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
if let Ok(sink) = music_controller.get_single() {
sink.set_speed(((time.elapsed_seconds() / 5.0).sin() + 1.0).max(0.1));
}
}
fn pause(
keyboard_input: Res<ButtonInput<KeyCode>>,
music_controller: Query<&AudioSink, With<MyMusic>>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
if let Ok(sink) = music_controller.get_single() {
sink.toggle();
}
}
}
fn volume(
keyboard_input: Res<ButtonInput<KeyCode>>,
music_controller: Query<&AudioSink, With<MyMusic>>,
) {
if let Ok(sink) = music_controller.get_single() {
if keyboard_input.just_pressed(KeyCode::Equal) {
sink.set_volume(sink.volume() + 0.1);
} else if keyboard_input.just_pressed(KeyCode::Minus) {
sink.set_volume(sink.volume() - 0.1);
}
}
}
More examples
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
fn environment_map_load_finish(
mut commands: Commands,
asset_server: Res<AssetServer>,
environment_maps: Query<&EnvironmentMapLight>,
label_query: Query<Entity, With<EnvironmentMapLabel>>,
) {
if let Ok(environment_map) = environment_maps.get_single() {
if asset_server.load_state(&environment_map.diffuse_map) == LoadState::Loaded
&& asset_server.load_state(&environment_map.specular_map) == LoadState::Loaded
{
if let Ok(label_entity) = label_query.get_single() {
commands.entity(label_entity).despawn();
}
}
}
}
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
fn drag_drop_image(
image_mat: Query<&Handle<StandardMaterial>, With<HDRViewer>>,
text: Query<Entity, (With<Text>, With<SceneNumber>)>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut drop_events: EventReader<FileDragAndDrop>,
asset_server: Res<AssetServer>,
mut commands: Commands,
) {
let Some(new_image) = drop_events.read().find_map(|e| match e {
FileDragAndDrop::DroppedFile { path_buf, .. } => {
Some(asset_server.load(path_buf.to_string_lossy().to_string()))
}
_ => None,
}) else {
return;
};
for mat_h in &image_mat {
if let Some(mat) = materials.get_mut(mat_h) {
mat.base_color_texture = Some(new_image.clone());
// Despawn the image viewer instructions
if let Ok(text_entity) = text.get_single() {
commands.entity(text_entity).despawn();
}
}
}
}
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
fn input_handler(
keyboard_input: Res<ButtonInput<KeyCode>>,
mesh_query: Query<&Handle<Mesh>, With<CustomUV>>,
mut meshes: ResMut<Assets<Mesh>>,
mut query: Query<&mut Transform, With<CustomUV>>,
time: Res<Time>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
let mesh_handle = mesh_query.get_single().expect("Query not successful");
let mesh = meshes.get_mut(mesh_handle).unwrap();
toggle_texture(mesh);
}
if keyboard_input.pressed(KeyCode::KeyX) {
for mut transform in &mut query {
transform.rotate_x(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyY) {
for mut transform in &mut query {
transform.rotate_y(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyZ) {
for mut transform in &mut query {
transform.rotate_z(time.delta_seconds() / 1.2);
}
}
if keyboard_input.pressed(KeyCode::KeyR) {
for mut transform in &mut query {
transform.look_to(Vec3::NEG_Z, Vec3::Y);
}
}
}
sourcepub fn single_mut(&mut self) -> <D as WorldQuery>::Item<'_>
pub fn single_mut(&mut self) -> <D as WorldQuery>::Item<'_>
Returns a single query item when there is exactly one entity matching the query.
§Panics
This method panics if the number of query item is not exactly one.
§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
let mut health = query.single_mut();
health.0 += 1;
}
§See also
get_single_mut
for the non-panicking version.single
to get the read-only query item.
Examples found in repository?
More examples
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
fn display_override(mut windows: Query<&mut Window>) {
let mut window = windows.single_mut();
window.title = format!(
"Scale override: {:?}",
window.resolution.scale_factor_override()
);
}
/// This system toggles scale factor overrides when enter is pressed
fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut windows: Query<&mut Window>) {
let mut window = windows.single_mut();
if input.just_pressed(KeyCode::Enter) {
let scale_factor_override = window.resolution.scale_factor_override();
window
.resolution
.set_scale_factor_override(scale_factor_override.xor(Some(1.0)));
}
}
/// This system changes the scale factor override when up or down is pressed
fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut windows: Query<&mut Window>) {
let mut window = windows.single_mut();
let scale_factor_override = window.resolution.scale_factor_override();
if input.just_pressed(KeyCode::ArrowUp) {
window
.resolution
.set_scale_factor_override(scale_factor_override.map(|n| n + 1.0));
} else if input.just_pressed(KeyCode::ArrowDown) {
window
.resolution
.set_scale_factor_override(scale_factor_override.map(|n| (n - 1.0).max(1.0)));
}
}
- examples/ui/window_fallthrough.rs
- examples/stress_tests/many_sprites.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/ecs/iter_combinations.rs
- examples/stress_tests/many_cubes.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/atmospheric_fog.rs
- examples/window/window_settings.rs
- examples/3d/spotlight.rs
- examples/input/text_input.rs
- examples/input/mouse_grab.rs
- examples/stress_tests/many_gizmos.rs
- examples/2d/bounding_2d.rs
- examples/window/window_resizing.rs
- examples/window/low_power.rs
- examples/audio/spatial_audio_3d.rs
- examples/audio/spatial_audio_2d.rs
- examples/stress_tests/bevymark.rs
- examples/ui/relative_cursor_position.rs
- examples/math/render_primitives.rs
- examples/3d/deterministic.rs
- examples/3d/shadow_biases.rs
- examples/games/game_menu.rs
- examples/games/breakout.rs
- examples/shader/shader_prepass.rs
- examples/3d/parallax_mapping.rs
- examples/3d/tonemapping.rs
- examples/games/contributors.rs
- examples/games/stepping.rs
- examples/3d/wireframe.rs
- examples/3d/lighting.rs
- examples/3d/split_screen.rs
- examples/2d/rotation.rs
- examples/3d/blend_modes.rs
- examples/3d/anti_aliasing.rs
- examples/ui/size_constraints.rs
- examples/3d/ssao.rs
- examples/3d/deferred_rendering.rs
- examples/3d/bloom_3d.rs
- examples/2d/bloom_2d.rs
- examples/3d/fog.rs
- examples/3d/transmission.rs
sourcepub fn get_single_mut(
&mut self
) -> Result<<D as WorldQuery>::Item<'_>, QuerySingleError>
pub fn get_single_mut( &mut self ) -> Result<<D as WorldQuery>::Item<'_>, QuerySingleError>
Returns a single query item when there is exactly one entity matching the query.
If the number of query items is not exactly one, a QuerySingleError
is returned instead.
§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
let mut health = query.get_single_mut().expect("Error: Could not find a single player.");
health.0 += 1;
}
§See also
get_single
to get the read-only query item.single_mut
for the panicking version.
Examples found in repository?
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
fn run_camera_controller(
time: Res<Time>,
mut windows: Query<&mut Window>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut toggle_cursor_grab: Local<bool>,
mut mouse_cursor_grab: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut controller)) = query.get_single_mut() {
if !controller.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
controller.yaw = yaw;
controller.pitch = pitch;
controller.initialized = true;
info!("{}", *controller);
}
if !controller.enabled {
mouse_events.clear();
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(controller.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(controller.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(controller.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(controller.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(controller.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(controller.key_down) {
axis_input.y -= 1.0;
}
let mut cursor_grab_change = false;
if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
*toggle_cursor_grab = !*toggle_cursor_grab;
cursor_grab_change = true;
}
if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = true;
cursor_grab_change = true;
}
if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = false;
cursor_grab_change = true;
}
let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(controller.key_run) {
controller.run_speed
} else {
controller.walk_speed
};
controller.velocity = axis_input.normalize() * max_speed;
} else {
let friction = controller.friction.clamp(0.0, 1.0);
controller.velocity *= 1.0 - friction;
if controller.velocity.length_squared() < 1e-6 {
controller.velocity = Vec3::ZERO;
}
}
let forward = *transform.forward();
let right = *transform.right();
transform.translation += controller.velocity.x * dt * right
+ controller.velocity.y * dt * Vec3::Y
+ controller.velocity.z * dt * forward;
// Handle cursor grab
if cursor_grab_change {
if cursor_grab {
for mut window in &mut windows {
if !window.focused {
continue;
}
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
} else {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
}
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if cursor_grab {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
} else {
mouse_events.clear();
}
if mouse_delta != Vec2::ZERO {
// Apply look update
controller.pitch = (controller.pitch
- mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
.clamp(-PI / 2., PI / 2.);
controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
transform.rotation =
Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
}
}
}
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if there are no query items.
§Example
Here, the score is increased only if an entity with a Player
component is present in the world:
fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
if !query.is_empty() {
score.0 += 1;
}
}
Examples found in repository?
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
fn update_ui(
mut commands: Commands,
state: Res<State>,
stepping: Res<Stepping>,
mut ui: Query<(Entity, &mut Text, &Visibility), With<SteppingUi>>,
) {
if ui.is_empty() {
return;
}
// ensure the UI is only visible when stepping is enabled
let (ui, mut text, vis) = ui.single_mut();
match (vis, stepping.is_enabled()) {
(Visibility::Hidden, true) => {
commands.entity(ui).insert(Visibility::Inherited);
}
(Visibility::Hidden, false) | (_, true) => (),
(_, false) => {
commands.entity(ui).insert(Visibility::Hidden);
}
}
// if we're not stepping, there's nothing more to be done here.
if !stepping.is_enabled() {
return;
}
let (cursor_schedule, cursor_system) = match stepping.cursor() {
// no cursor means stepping isn't enabled, so we're done here
None => return,
Some(c) => c,
};
for (schedule, system, text_index) in &state.systems {
let mark = if &cursor_schedule == schedule && *system == cursor_system {
"-> "
} else {
" "
};
text.sections[*text_index].value = mark.to_string();
}
}
More examples
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
fn create_cubes(
image_assets: Res<Assets<Image>>,
mut commands: Commands,
irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
voxel_cubes: Query<Entity, With<VoxelCube>>,
example_assets: Res<ExampleAssets>,
mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
// If voxel cubes have already been spawned, don't do anything.
if !voxel_cubes.is_empty() {
return;
}
let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
return;
};
for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
continue;
};
let resolution = image.texture_descriptor.size;
let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
base: StandardMaterial::from(Color::RED),
extension: VoxelVisualizationExtension {
irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
transform: VOXEL_TRANSFORM.inverse(),
inverse_transform: VOXEL_TRANSFORM,
resolution: uvec3(
resolution.width,
resolution.height,
resolution.depth_or_array_layers,
),
intensity: IRRADIANCE_VOLUME_INTENSITY,
},
},
});
let scale = vec3(
1.0 / resolution.width as f32,
1.0 / resolution.height as f32,
1.0 / resolution.depth_or_array_layers as f32,
);
// Spawn a cube for each voxel.
for z in 0..resolution.depth_or_array_layers {
for y in 0..resolution.height {
for x in 0..resolution.width {
let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
let pos = global_transform.transform_point(uvw);
let voxel_cube = commands
.spawn(MaterialMeshBundle {
mesh: example_assets.voxel_cube.clone(),
material: voxel_cube_material.clone(),
transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
.with_translation(pos),
..default()
})
.insert(VoxelCube)
.insert(NotShadowCaster)
.id();
commands.entity(voxel_cube_parent).add_child(voxel_cube);
}
}
}
}
}
sourcepub fn transmute_lens<NewD>(&mut self) -> QueryLens<'_, NewD>where
NewD: QueryData,
pub fn transmute_lens<NewD>(&mut self) -> QueryLens<'_, NewD>where
NewD: QueryData,
Returns a QueryLens
that can be used to get a query with a more general fetch.
For example, this can transform a Query<(&A, &mut B)>
to a Query<&B>
.
This can be useful for passing the query to another function. Note that since
filter terms are dropped, non-archetypal filters like Added
and
Changed
will not be respected. To maintain or change filter
terms see Self::transmute_lens_filtered
§Panics
This will panic if NewD
is not a subset of the original fetch Q
§Example
fn reusable_function(lens: &mut QueryLens<&A>) {
assert_eq!(lens.query().single().0, 10);
}
// We can use the function in a system that takes the exact query.
fn system_1(mut query: Query<&A>) {
reusable_function(&mut query.as_query_lens());
}
// We can also use it with a query that does not match exactly
// by transmuting it.
fn system_2(mut query: Query<(&mut A, &B)>) {
let mut lens = query.transmute_lens::<&A>();
reusable_function(&mut lens);
}
§Allowed Transmutes
Besides removing parameters from the query, you can also make limited changes to the types of paramters.
sourcepub fn transmute_lens_filtered<NewD, NewF>(
&mut self
) -> QueryLens<'_, NewD, NewF>where
NewD: QueryData,
NewF: QueryFilter,
pub fn transmute_lens_filtered<NewD, NewF>(
&mut self
) -> QueryLens<'_, NewD, NewF>where
NewD: QueryData,
NewF: QueryFilter,
Equivalent to Self::transmute_lens
but also includes a QueryFilter
type.
Note that the lens will iterate the same tables and archetypes as the original query. This means that
additional archetypal query terms like With
and Without
will not necessarily be respected and non-archetypal terms like Added
and
Changed
will only be respected if they are in the type signature.
sourcepub fn as_query_lens(&mut self) -> QueryLens<'_, D>
pub fn as_query_lens(&mut self) -> QueryLens<'_, D>
Gets a QueryLens
with the same accesses as the existing query
source§impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: ReadOnlyQueryData,
F: QueryFilter,
impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: ReadOnlyQueryData,
F: QueryFilter,
sourcepub fn get_inner(
&self,
entity: Entity
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError>
pub fn get_inner( &self, entity: Entity ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError>
Returns the query item for the given Entity
, with the actual “inner” world lifetime.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is
returned instead.
This can only return immutable data (mutable data will be cast to an immutable form).
See get_mut
for queries that contain at least one mutable component.
§Example
Here, get
is used to retrieve the exact query item of the entity specified by the
SelectedCharacter
resource.
fn print_selected_character_name_system(
query: Query<&Character>,
selection: Res<SelectedCharacter>
)
{
if let Ok(selected_character) = query.get(selection.entity) {
println!("{}", selected_character.name);
}
}
sourcepub fn iter_inner(&self) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter_inner(&self) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator
over the query items, with the actual “inner” world lifetime.
This can only return immutable data (mutable data will be cast to an immutable form).
See Self::iter_mut
for queries that contain at least one mutable component.
§Example
Here, the report_names_system
iterates over the Player
component of every entity
that contains it:
fn report_names_system(query: Query<&Player>) {
for player in &query {
println!("Say hello to {}!", player.name);
}
}
Trait Implementations§
source§impl<'w, 'q, Q, F> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F>where
Q: QueryData,
F: QueryFilter,
impl<'w, 'q, Q, F> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F>where
Q: QueryData,
F: QueryFilter,
source§impl<'w, 's, Q, F> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F>where
Q: QueryData,
F: QueryFilter,
impl<'w, 's, Q, F> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F>where
Q: QueryData,
F: QueryFilter,
source§impl<'w, 's, D, F> HierarchyQueryExt<'w, 's, D, F> for Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> HierarchyQueryExt<'w, 's, D, F> for Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
source§fn iter_descendants(&'w self, entity: Entity) -> DescendantIter<'w, 's, D, F> ⓘ
fn iter_descendants(&'w self, entity: Entity) -> DescendantIter<'w, 's, D, F> ⓘ
source§fn iter_ancestors(&'w self, entity: Entity) -> AncestorIter<'w, 's, D, F> ⓘ
fn iter_ancestors(&'w self, entity: Entity) -> AncestorIter<'w, 's, D, F> ⓘ
source§impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
source§impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
§type Item = <D as WorldQuery>::Item<'w>
type Item = <D as WorldQuery>::Item<'w>
source§impl<D, F> SystemParam for Query<'_, '_, D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
impl<D, F> SystemParam for Query<'_, '_, D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
§type State = QueryState<D, F>
type State = QueryState<D, F>
§type Item<'w, 's> = Query<'w, 's, D, F>
type Item<'w, 's> = Query<'w, 's, D, F>
Self
, instantiated with new lifetimes. Read moresource§fn init_state(
world: &mut World,
system_meta: &mut SystemMeta
) -> <Query<'_, '_, D, F> as SystemParam>::State
fn init_state( world: &mut World, system_meta: &mut SystemMeta ) -> <Query<'_, '_, D, F> as SystemParam>::State
World
access used by this SystemParam
and creates a new instance of this param’s State
.source§fn new_archetype(
state: &mut <Query<'_, '_, D, F> as SystemParam>::State,
archetype: &Archetype,
system_meta: &mut SystemMeta
)
fn new_archetype( state: &mut <Query<'_, '_, D, F> as SystemParam>::State, archetype: &Archetype, system_meta: &mut SystemMeta )
Archetype
, registers the components accessed by this SystemParam
(if applicable).source§unsafe fn get_param<'w, 's>(
state: &'s mut <Query<'_, '_, D, F> as SystemParam>::State,
system_meta: &SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: Tick
) -> <Query<'_, '_, D, F> as SystemParam>::Item<'w, 's>
unsafe fn get_param<'w, 's>( state: &'s mut <Query<'_, '_, D, F> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick ) -> <Query<'_, '_, D, F> as SystemParam>::Item<'w, 's>
SystemParamFunction
. Read moresource§fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
SystemParam
’s state.
This is used to apply Commands
during apply_deferred
.impl<'w, 's, D, F> ReadOnlySystemParam for Query<'w, 's, D, F>where
D: ReadOnlyQueryData + 'static,
F: QueryFilter + 'static,
Auto Trait Implementations§
impl<'world, 'state, D, F> Freeze for Query<'world, 'state, D, F>where
F: WorldQuery,
D: WorldQuery,
impl<'world, 'state, D, F = ()> !RefUnwindSafe for Query<'world, 'state, D, F>
impl<'world, 'state, D, F> Send for Query<'world, 'state, D, F>where
F: WorldQuery,
D: WorldQuery,
impl<'world, 'state, D, F> Sync for Query<'world, 'state, D, F>where
F: WorldQuery,
D: WorldQuery,
impl<'world, 'state, D, F> Unpin for Query<'world, 'state, D, F>where
F: WorldQuery,
D: WorldQuery,
impl<'world, 'state, D, F = ()> !UnwindSafe for Query<'world, 'state, D, F>
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.