Struct bevy::ecs::system::EntityCommands
pub struct EntityCommands<'a> { /* private fields */ }
Expand description
A list of commands that will be run to modify an entity.
Implementations§
§impl EntityCommands<'_>
impl EntityCommands<'_>
pub fn id(&self) -> Entity
pub fn id(&self) -> Entity
Returns the Entity
id of the entity.
§Example
fn my_system(mut commands: Commands) {
let entity_id = commands.spawn_empty().id();
}
Examples found in repository?
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
fn setup_menu(mut commands: Commands) {
let button_entity = commands
.spawn(NodeBundle {
style: Style {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
})
.with_children(|parent| {
parent
.spawn(ButtonBundle {
style: Style {
width: Val::Px(150.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
background_color: NORMAL_BUTTON.into(),
..default()
})
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Play",
TextStyle {
font_size: 40.0,
color: Color::rgb(0.9, 0.9, 0.9),
..default()
},
));
});
})
.id();
commands.insert_resource(MenuData { button_entity });
}
More examples
15 16 17 18 19 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 53 54 55 56 57 58
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
let texture = asset_server.load("branding/icon.png");
// Spawn a root entity with no parent
let parent = commands
.spawn(SpriteBundle {
transform: Transform::from_scale(Vec3::splat(0.75)),
texture: texture.clone(),
..default()
})
// With that entity as a parent, run a lambda that spawns its children
.with_children(|parent| {
// parent is a ChildBuilder, which has a similar API to Commands
parent.spawn(SpriteBundle {
transform: Transform::from_xyz(250.0, 0.0, 0.0).with_scale(Vec3::splat(0.75)),
texture: texture.clone(),
sprite: Sprite {
color: Color::BLUE,
..default()
},
..default()
});
})
// Store parent entity for next sections
.id();
// Another way is to use the push_children function to add children after the parent
// entity has already been spawned.
let child = commands
.spawn(SpriteBundle {
transform: Transform::from_xyz(0.0, 250.0, 0.0).with_scale(Vec3::splat(0.75)),
texture,
sprite: Sprite {
color: Color::GREEN,
..default()
},
..default()
})
.id();
// Add child to the parent.
commands.entity(parent).add_child(child);
}
14 15 16 17 18 19 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
// add entities to the world
commands.spawn(SceneBundle {
scene: asset_server.load("models/torus/torus.gltf#Scene0"),
..default()
});
// light
commands.spawn(DirectionalLightBundle {
transform: Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
});
let first_window_camera = commands
.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 6.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
})
.id();
// Spawn a second window
let second_window = commands
.spawn(Window {
title: "Second window".to_owned(),
..default()
})
.id();
let second_window_camera = commands
.spawn(Camera3dBundle {
transform: Transform::from_xyz(6.0, 0.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
camera: Camera {
target: RenderTarget::Window(WindowRef::Entity(second_window)),
..default()
},
..default()
})
.id();
// Since we are using multiple cameras, we need to specify which camera UI should be rendered to
commands
.spawn((NodeBundle::default(), TargetCamera(first_window_camera)))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"First window",
TextStyle::default(),
));
});
commands
.spawn((NodeBundle::default(), TargetCamera(second_window_camera)))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Second window",
TextStyle::default(),
));
});
}
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
fn setup_contributor_selection(mut commands: Commands, asset_server: Res<AssetServer>) {
// Load contributors from the git history log or use default values from
// the constant array. Contributors must be unique, so they are stored in a HashSet
let contribs = contributors().unwrap_or_else(|_| {
CONTRIBUTORS_LIST
.iter()
.map(|name| name.to_string())
.collect()
});
let texture_handle = asset_server.load("branding/icon.png");
let mut contributor_selection = ContributorSelection {
order: Vec::with_capacity(contribs.len()),
idx: 0,
};
let mut rng = rand::thread_rng();
for name in contribs {
let pos = (rng.gen_range(-400.0..400.0), rng.gen_range(0.0..400.0));
let dir = rng.gen_range(-1.0..1.0);
let velocity = Vec3::new(dir * 500.0, 0.0, 0.0);
let hue = rng.gen_range(0.0..=360.0);
// some sprites should be flipped
let flipped = rng.gen_bool(0.5);
let transform = Transform::from_xyz(pos.0, pos.1, 0.0);
let entity = commands
.spawn((
Contributor { name, hue },
Velocity {
translation: velocity,
rotation: -dir * 5.0,
},
SpriteBundle {
sprite: Sprite {
custom_size: Some(Vec2::new(1.0, 1.0) * SPRITE_SIZE),
color: Color::hsla(hue, SATURATION_DESELECTED, LIGHTNESS_DESELECTED, ALPHA),
flip_x: flipped,
..default()
},
texture: texture_handle.clone(),
transform,
..default()
},
))
.id();
contributor_selection.order.push(entity);
}
contributor_selection.order.shuffle(&mut rng);
commands.insert_resource(contributor_selection);
}
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
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
// reset the game state
game.cake_eaten = 0;
game.score = 0;
game.player.i = BOARD_SIZE_I / 2;
game.player.j = BOARD_SIZE_J / 2;
game.player.move_cooldown = Timer::from_seconds(0.3, TimerMode::Once);
commands.spawn(PointLightBundle {
transform: Transform::from_xyz(4.0, 10.0, 4.0),
point_light: PointLight {
intensity: 2_000_000.0,
shadows_enabled: true,
range: 30.0,
..default()
},
..default()
});
// spawn the game board
let cell_scene = asset_server.load("models/AlienCake/tile.glb#Scene0");
game.board = (0..BOARD_SIZE_J)
.map(|j| {
(0..BOARD_SIZE_I)
.map(|i| {
let height = rand::thread_rng().gen_range(-0.1..0.1);
commands.spawn(SceneBundle {
transform: Transform::from_xyz(i as f32, height - 0.2, j as f32),
scene: cell_scene.clone(),
..default()
});
Cell { height }
})
.collect()
})
.collect();
// spawn the game character
game.player.entity = Some(
commands
.spawn(SceneBundle {
transform: Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(-PI / 2.),
..default()
},
scene: asset_server.load("models/AlienCake/alien.glb#Scene0"),
..default()
})
.id(),
);
// load the scene for the cake
game.bonus.handle = asset_server.load("models/AlienCake/cakeBirthday.glb#Scene0");
// scoreboard
commands.spawn(
TextBundle::from_section(
"Score:",
TextStyle {
font_size: 40.0,
color: Color::rgb(0.5, 0.5, 1.0),
..default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(5.0),
left: Val::Px(5.0),
..default()
}),
);
}
// remove all entities that are not a camera or window
fn teardown(mut commands: Commands, entities: Query<Entity, (Without<Camera>, Without<Window>)>) {
for entity in &entities {
commands.entity(entity).despawn();
}
}
// control the game character
fn move_player(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut game: ResMut<Game>,
mut transforms: Query<&mut Transform>,
time: Res<Time>,
) {
if game.player.move_cooldown.tick(time.delta()).finished() {
let mut moved = false;
let mut rotation = 0.0;
if keyboard_input.pressed(KeyCode::ArrowUp) {
if game.player.i < BOARD_SIZE_I - 1 {
game.player.i += 1;
}
rotation = -PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
if game.player.i > 0 {
game.player.i -= 1;
}
rotation = PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
if game.player.j < BOARD_SIZE_J - 1 {
game.player.j += 1;
}
rotation = PI;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
if game.player.j > 0 {
game.player.j -= 1;
}
rotation = 0.0;
moved = true;
}
// move on the board
if moved {
game.player.move_cooldown.reset();
*transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(rotation),
..default()
};
}
}
// eat the cake!
if let Some(entity) = game.bonus.entity {
if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
game.score += 2;
game.cake_eaten += 1;
commands.entity(entity).despawn_recursive();
game.bonus.entity = None;
}
}
}
// change the focus of the camera
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);
}
}
// despawn the bonus if there is one, then spawn a new one at a random location
fn spawn_bonus(
time: Res<Time>,
mut timer: ResMut<BonusSpawnTimer>,
mut next_state: ResMut<NextState<GameState>>,
mut commands: Commands,
mut game: ResMut<Game>,
) {
// make sure we wait enough time before spawning the next cake
if !timer.0.tick(time.delta()).finished() {
return;
}
if let Some(entity) = game.bonus.entity {
game.score -= 3;
commands.entity(entity).despawn_recursive();
game.bonus.entity = None;
if game.score <= -5 {
next_state.set(GameState::GameOver);
return;
}
}
// ensure bonus doesn't spawn on the player
loop {
game.bonus.i = rand::thread_rng().gen_range(0..BOARD_SIZE_I);
game.bonus.j = rand::thread_rng().gen_range(0..BOARD_SIZE_J);
if game.bonus.i != game.player.i || game.bonus.j != game.player.j {
break;
}
}
game.bonus.entity = Some(
commands
.spawn(SceneBundle {
transform: Transform::from_xyz(
game.bonus.i as f32,
game.board[game.bonus.j][game.bonus.i].height + 0.2,
game.bonus.j as f32,
),
scene: game.bonus.handle.clone(),
..default()
})
.with_children(|children| {
children.spawn(PointLightBundle {
point_light: PointLight {
color: Color::rgb(1.0, 1.0, 0.0),
intensity: 500_000.0,
range: 10.0,
..default()
},
transform: Transform::from_xyz(0.0, 2.0, 0.0),
..default()
});
})
.id(),
);
}
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
fn spawn_tasks(mut commands: Commands) {
let thread_pool = AsyncComputeTaskPool::get();
for x in 0..NUM_CUBES {
for y in 0..NUM_CUBES {
for z in 0..NUM_CUBES {
// Spawn new task on the AsyncComputeTaskPool; the task will be
// executed in the background, and the Task future returned by
// spawn() can be used to poll for the result
let entity = commands.spawn_empty().id();
let task = thread_pool.spawn(async move {
let mut rng = rand::thread_rng();
let duration = Duration::from_secs_f32(rng.gen_range(0.05..0.2));
// Pretend this is a time-intensive function. :)
thread::sleep(duration);
// Such hard work, all done!
let transform = Transform::from_xyz(x as f32, y as f32, z as f32);
let mut command_queue = CommandQueue::default();
// we use a raw command queue to pass a FnOne(&mut World) back to be
// applied in a deferred manner.
command_queue.push(move |world: &mut World| {
let (box_mesh_handle, box_material_handle) = {
let mut system_state = SystemState::<(
Res<BoxMeshHandle>,
Res<BoxMaterialHandle>,
)>::new(world);
let (box_mesh_handle, box_material_handle) =
system_state.get_mut(world);
(box_mesh_handle.clone(), box_material_handle.clone())
};
world
.entity_mut(entity)
// Add our new PbrBundle of components to our tagged entity
.insert(PbrBundle {
mesh: box_mesh_handle,
material: box_material_handle,
transform,
..default()
})
// Task is complete, so remove task component from entity
.remove::<ComputeTransform>();
});
command_queue
});
// Spawn new entity and add our new task as a component
commands.entity(entity).insert(ComputeTransform(task));
}
}
}
}
- examples/3d/irradiance_volumes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/ui/render_ui_to_texture.rs
- examples/ui/text_wrap_debug.rs
- examples/ui/borders.rs
- examples/stress_tests/many_foxes.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/split_screen.rs
- examples/ui/display_and_visibility.rs
- examples/ui/text_debug.rs
- examples/3d/blend_modes.rs
pub fn reborrow(&mut self) -> EntityCommands<'_>
pub fn reborrow(&mut self) -> EntityCommands<'_>
Returns an EntityCommands
with a smaller lifetime.
This is useful if you have &mut EntityCommands
but you need EntityCommands
.
pub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'_>
pub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'_>
Adds a Bundle
of components to the entity.
This will overwrite any previous value(s) of the same component type.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert
instead.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can insert individual components:
.insert(Defense(10))
// You can also insert pre-defined bundles of components:
.insert(CombatBundle {
health: Health(100),
strength: Strength(40),
})
// You can also insert tuples of components and bundles.
// This is equivalent to the calls above:
.insert((
Defense(10),
CombatBundle {
health: Health(100),
strength: Strength(40),
},
));
}
Examples found in repository?
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 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
fn spawn_camera(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(Camera3dBundle {
transform: Transform::from_xyz(-10.012, 4.8605, 13.281).looking_at(Vec3::ZERO, Vec3::Y),
..default()
})
.insert(Skybox {
image: assets.skybox.clone(),
brightness: 150.0,
});
}
fn spawn_irradiance_volume(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(SpatialBundle {
transform: Transform::from_matrix(VOXEL_TRANSFORM),
..SpatialBundle::default()
})
.insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
})
.insert(LightProbe);
}
fn spawn_light(commands: &mut Commands) {
commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 250000.0,
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0762, 5.9039, 1.0055),
..default()
});
}
fn spawn_sphere(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(PbrBundle {
mesh: assets.main_sphere.clone(),
material: assets.main_sphere_material.clone(),
transform: Transform::from_xyz(0.0, SPHERE_SCALE, 0.0)
.with_scale(Vec3::splat(SPHERE_SCALE)),
..default()
})
.insert(MainObject);
}
fn spawn_voxel_cube_parent(commands: &mut Commands) {
commands
.spawn(SpatialBundle {
visibility: Visibility::Hidden,
..default()
})
.insert(VoxelCubeParent);
}
fn spawn_fox(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn(SceneBundle {
scene: assets.fox.clone(),
visibility: Visibility::Hidden,
transform: Transform::from_scale(Vec3::splat(FOX_SCALE)),
..default()
})
.insert(MainObject);
}
fn spawn_text(commands: &mut Commands, app_status: &AppStatus, asset_server: &AssetServer) {
commands.spawn(
TextBundle {
text: app_status.create_text(asset_server),
..TextBundle::default()
}
.with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::Px(10.0),
left: Val::Px(10.0),
..default()
}),
);
}
// A system that updates the help text.
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);
}
}
}
}
}
More examples
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
fn add_environment_map_to_camera(
mut commands: Commands,
query: Query<Entity, Added<Camera3d>>,
cubemaps: Res<Cubemaps>,
) {
for camera_entity in query.iter() {
commands
.entity(camera_entity)
.insert(create_camera_environment_map_light(&cubemaps))
.insert(Skybox {
image: cubemaps.skybox.clone(),
brightness: 5000.0,
});
}
}
// A system that handles switching between different reflection modes.
fn change_reflection_type(
mut commands: Commands,
light_probe_query: Query<Entity, With<LightProbe>>,
camera_query: Query<Entity, With<Camera3d>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
cubemaps: Res<Cubemaps>,
) {
// Only do anything if space was pressed.
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
// Switch reflection mode.
app_status.reflection_mode =
ReflectionMode::try_from((app_status.reflection_mode as u32 + 1) % 3).unwrap();
// Add or remove the light probe.
for light_probe in light_probe_query.iter() {
commands.entity(light_probe).despawn();
}
match app_status.reflection_mode {
ReflectionMode::None | ReflectionMode::EnvironmentMap => {}
ReflectionMode::ReflectionProbe => spawn_reflection_probe(&mut commands, &cubemaps),
}
// Add or remove the environment map from the camera.
for camera in camera_query.iter() {
match app_status.reflection_mode {
ReflectionMode::None => {
commands.entity(camera).remove::<EnvironmentMapLight>();
}
ReflectionMode::EnvironmentMap | ReflectionMode::ReflectionProbe => {
commands
.entity(camera)
.insert(create_camera_environment_map_light(&cubemaps));
}
}
}
}
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
fn decompress<A: Asset>(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut compressed_assets: ResMut<Assets<GzAsset>>,
query: Query<(Entity, &Compressed<A>)>,
) {
for (entity, Compressed { compressed, .. }) in query.iter() {
let Some(GzAsset { uncompressed }) = compressed_assets.remove(compressed) else {
continue;
};
let uncompressed = uncompressed.take::<A>().unwrap();
commands
.entity(entity)
.remove::<Compressed<A>>()
.insert(asset_server.add(uncompressed));
}
}
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
fn prepare_instance_buffers(
mut commands: Commands,
query: Query<(Entity, &InstanceMaterialData)>,
render_device: Res<RenderDevice>,
) {
for (entity, instance_data) in &query {
let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
label: Some("instance data buffer"),
contents: bytemuck::cast_slice(instance_data.as_slice()),
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
});
commands.entity(entity).insert(InstanceBuffer {
buffer,
length: instance_data.len(),
});
}
}
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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
fn setting_button<T: Resource + Component + PartialEq + Copy>(
interaction_query: Query<(&Interaction, &T, Entity), (Changed<Interaction>, With<Button>)>,
mut selected_query: Query<(Entity, &mut BackgroundColor), With<SelectedOption>>,
mut commands: Commands,
mut setting: ResMut<T>,
) {
for (interaction, button_setting, entity) in &interaction_query {
if *interaction == Interaction::Pressed && *setting != *button_setting {
let (previous_button, mut previous_color) = selected_query.single_mut();
*previous_color = NORMAL_BUTTON.into();
commands.entity(previous_button).remove::<SelectedOption>();
commands.entity(entity).insert(SelectedOption);
*setting = *button_setting;
}
}
}
fn menu_setup(mut menu_state: ResMut<NextState<MenuState>>) {
menu_state.set(MenuState::Main);
}
fn main_menu_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Common style for all buttons on the screen
let button_style = Style {
width: Val::Px(250.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_icon_style = Style {
width: Val::Px(30.0),
// This takes the icons out of the flexbox flow, to be positioned exactly
position_type: PositionType::Absolute,
// The icon will be close to the left border of the button
left: Val::Px(10.0),
..default()
};
let button_text_style = TextStyle {
font_size: 40.0,
color: TEXT_COLOR,
..default()
};
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnMainMenuScreen,
))
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
// Display the game name
parent.spawn(
TextBundle::from_section(
"Bevy Game Menu UI",
TextStyle {
font_size: 80.0,
color: TEXT_COLOR,
..default()
},
)
.with_style(Style {
margin: UiRect::all(Val::Px(50.0)),
..default()
}),
);
// Display three buttons for each action available from the main menu:
// - new game
// - settings
// - quit
parent
.spawn((
ButtonBundle {
style: button_style.clone(),
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButtonAction::Play,
))
.with_children(|parent| {
let icon = asset_server.load("textures/Game Icons/right.png");
parent.spawn(ImageBundle {
style: button_icon_style.clone(),
image: UiImage::new(icon),
..default()
});
parent.spawn(TextBundle::from_section(
"New Game",
button_text_style.clone(),
));
});
parent
.spawn((
ButtonBundle {
style: button_style.clone(),
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButtonAction::Settings,
))
.with_children(|parent| {
let icon = asset_server.load("textures/Game Icons/wrench.png");
parent.spawn(ImageBundle {
style: button_icon_style.clone(),
image: UiImage::new(icon),
..default()
});
parent.spawn(TextBundle::from_section(
"Settings",
button_text_style.clone(),
));
});
parent
.spawn((
ButtonBundle {
style: button_style,
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButtonAction::Quit,
))
.with_children(|parent| {
let icon = asset_server.load("textures/Game Icons/exitRight.png");
parent.spawn(ImageBundle {
style: button_icon_style,
image: UiImage::new(icon),
..default()
});
parent.spawn(TextBundle::from_section("Quit", button_text_style));
});
});
});
}
fn settings_menu_setup(mut commands: Commands) {
let button_style = Style {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_text_style = TextStyle {
font_size: 40.0,
color: TEXT_COLOR,
..default()
};
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnSettingsMenuScreen,
))
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
for (action, text) in [
(MenuButtonAction::SettingsDisplay, "Display"),
(MenuButtonAction::SettingsSound, "Sound"),
(MenuButtonAction::BackToMainMenu, "Back"),
] {
parent
.spawn((
ButtonBundle {
style: button_style.clone(),
background_color: NORMAL_BUTTON.into(),
..default()
},
action,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
text,
button_text_style.clone(),
));
});
}
});
});
}
fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) {
let button_style = Style {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_text_style = TextStyle {
font_size: 40.0,
color: TEXT_COLOR,
..default()
};
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnDisplaySettingsMenuScreen,
))
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
// Create a new `NodeBundle`, this time not setting its `flex_direction`. It will
// use the default value, `FlexDirection::Row`, from left to right.
parent
.spawn(NodeBundle {
style: Style {
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
// Display a label for the current setting
parent.spawn(TextBundle::from_section(
"Display Quality",
button_text_style.clone(),
));
// Display a button for each possible value
for quality_setting in [
DisplayQuality::Low,
DisplayQuality::Medium,
DisplayQuality::High,
] {
let mut entity = parent.spawn((
ButtonBundle {
style: Style {
width: Val::Px(150.0),
height: Val::Px(65.0),
..button_style.clone()
},
background_color: NORMAL_BUTTON.into(),
..default()
},
quality_setting,
));
entity.with_children(|parent| {
parent.spawn(TextBundle::from_section(
format!("{quality_setting:?}"),
button_text_style.clone(),
));
});
if *display_quality == quality_setting {
entity.insert(SelectedOption);
}
}
});
// Display the back button to return to the settings screen
parent
.spawn((
ButtonBundle {
style: button_style,
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButtonAction::BackToSettings,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section("Back", button_text_style));
});
});
});
}
fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) {
let button_style = Style {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_text_style = TextStyle {
font_size: 40.0,
color: TEXT_COLOR,
..default()
};
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnSoundSettingsMenuScreen,
))
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
parent
.spawn(NodeBundle {
style: Style {
align_items: AlignItems::Center,
..default()
},
background_color: Color::CRIMSON.into(),
..default()
})
.with_children(|parent| {
parent.spawn(TextBundle::from_section(
"Volume",
button_text_style.clone(),
));
for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
let mut entity = parent.spawn((
ButtonBundle {
style: Style {
width: Val::Px(30.0),
height: Val::Px(65.0),
..button_style.clone()
},
background_color: NORMAL_BUTTON.into(),
..default()
},
Volume(volume_setting),
));
if *volume == Volume(volume_setting) {
entity.insert(SelectedOption);
}
}
});
parent
.spawn((
ButtonBundle {
style: button_style,
background_color: NORMAL_BUTTON.into(),
..default()
},
MenuButtonAction::BackToSettings,
))
.with_children(|parent| {
parent.spawn(TextBundle::from_section("Back", button_text_style));
});
});
});
}
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,
}
}
}
- examples/3d/shadow_caster_receiver.rs
- examples/games/stepping.rs
- examples/stress_tests/many_buttons.rs
- examples/3d/tonemapping.rs
- examples/3d/lightmaps.rs
- examples/ui/relative_cursor_position.rs
- examples/2d/bounding_2d.rs
- examples/3d/anti_aliasing.rs
- examples/3d/ssao.rs
- examples/async_tasks/async_compute.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/3d/deferred_rendering.rs
- examples/2d/sprite_slice.rs
- examples/2d/bloom_2d.rs
- examples/3d/bloom_3d.rs
- examples/3d/transmission.rs
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'_>
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'_>
Tries to add a Bundle
of components to the entity.
This will overwrite any previous value(s) of the same component type.
§Note
Unlike Self::insert
, this will not panic if the associated entity does not exist.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands.entity(player.entity)
// You can try_insert individual components:
.try_insert(Defense(10))
// You can also insert tuples of components:
.try_insert(CombatBundle {
health: Health(100),
strength: Strength(40),
});
// Suppose this occurs in a parallel adjacent system or process
commands.entity(player.entity)
.despawn();
commands.entity(player.entity)
// This will not panic nor will it add the component
.try_insert(Defense(5));
}
pub fn remove<T>(&mut self) -> &mut EntityCommands<'_>where
T: Bundle,
pub fn remove<T>(&mut self) -> &mut EntityCommands<'_>where
T: Bundle,
Removes a Bundle
of components from the entity.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can remove individual components:
.remove::<Defense>()
// You can also remove pre-defined Bundles of components:
.remove::<CombatBundle>()
// You can also remove tuples of components and bundles.
// This is equivalent to the calls above:
.remove::<(Defense, CombatBundle)>();
}
Examples found in repository?
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>();
}
}
}
More examples
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
fn decompress<A: Asset>(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut compressed_assets: ResMut<Assets<GzAsset>>,
query: Query<(Entity, &Compressed<A>)>,
) {
for (entity, Compressed { compressed, .. }) in query.iter() {
let Some(GzAsset { uncompressed }) = compressed_assets.remove(compressed) else {
continue;
};
let uncompressed = uncompressed.take::<A>().unwrap();
commands
.entity(entity)
.remove::<Compressed<A>>()
.insert(asset_server.add(uncompressed));
}
}
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
fn setting_button<T: Resource + Component + PartialEq + Copy>(
interaction_query: Query<(&Interaction, &T, Entity), (Changed<Interaction>, With<Button>)>,
mut selected_query: Query<(Entity, &mut BackgroundColor), With<SelectedOption>>,
mut commands: Commands,
mut setting: ResMut<T>,
) {
for (interaction, button_setting, entity) in &interaction_query {
if *interaction == Interaction::Pressed && *setting != *button_setting {
let (previous_button, mut previous_color) = selected_query.single_mut();
*previous_color = NORMAL_BUTTON.into();
commands.entity(previous_button).remove::<SelectedOption>();
commands.entity(entity).insert(SelectedOption);
*setting = *button_setting;
}
}
}
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
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;
}
}
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
fn toggle_shadows(
mut commands: Commands,
input: Res<ButtonInput<KeyCode>>,
mut queries: ParamSet<(
Query<Entity, (With<Handle<Mesh>>, With<NotShadowCaster>)>,
Query<Entity, (With<Handle<Mesh>>, With<NotShadowReceiver>)>,
Query<Entity, (With<Handle<Mesh>>, Without<NotShadowCaster>)>,
Query<Entity, (With<Handle<Mesh>>, Without<NotShadowReceiver>)>,
)>,
) {
if input.just_pressed(KeyCode::KeyC) {
println!("Toggling casters");
for entity in queries.p0().iter() {
commands.entity(entity).remove::<NotShadowCaster>();
}
for entity in queries.p2().iter() {
commands.entity(entity).insert(NotShadowCaster);
}
}
if input.just_pressed(KeyCode::KeyR) {
println!("Toggling receivers");
for entity in queries.p1().iter() {
commands.entity(entity).remove::<NotShadowReceiver>();
}
for entity in queries.p3().iter() {
commands.entity(entity).insert(NotShadowReceiver);
}
}
}
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
fn change_reflection_type(
mut commands: Commands,
light_probe_query: Query<Entity, With<LightProbe>>,
camera_query: Query<Entity, With<Camera3d>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
cubemaps: Res<Cubemaps>,
) {
// Only do anything if space was pressed.
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
// Switch reflection mode.
app_status.reflection_mode =
ReflectionMode::try_from((app_status.reflection_mode as u32 + 1) % 3).unwrap();
// Add or remove the light probe.
for light_probe in light_probe_query.iter() {
commands.entity(light_probe).despawn();
}
match app_status.reflection_mode {
ReflectionMode::None | ReflectionMode::EnvironmentMap => {}
ReflectionMode::ReflectionProbe => spawn_reflection_probe(&mut commands, &cubemaps),
}
// Add or remove the environment map from the camera.
for camera in camera_query.iter() {
match app_status.reflection_mode {
ReflectionMode::None => {
commands.entity(camera).remove::<EnvironmentMapLight>();
}
ReflectionMode::EnvironmentMap | ReflectionMode::ReflectionProbe => {
commands
.entity(camera)
.insert(create_camera_environment_map_light(&cubemaps));
}
}
}
}
pub fn despawn(&mut self)
pub fn despawn(&mut self)
Despawns the entity.
See World::despawn
for more details.
§Note
This won’t clean up external references to the entity (such as parent-child relationships
if you’re using bevy_hierarchy
), which may leave the world in an invalid state.
§Panics
The command will panic when applied if the associated entity does not exist.
§Example
fn remove_character_system(
mut commands: Commands,
character_to_remove: Res<CharacterToRemove>
)
{
commands.entity(character_to_remove.entity).despawn();
}
Examples found in repository?
More examples
70 71 72 73 74 75 76 77 78 79 80 81
fn move_text(
mut commands: Commands,
mut texts: Query<(Entity, &mut Transform), With<Text>>,
time: Res<Time>,
) {
for (entity, mut position) in &mut texts {
position.translation -= Vec3::new(0.0, 100.0 * time.delta_seconds(), 0.0);
if position.translation.y < -300.0 {
commands.entity(entity).despawn();
}
}
}
127 128 129 130 131 132 133 134 135 136 137 138
fn bubbling_text(
mut commands: Commands,
mut bubbles: Query<(Entity, &mut Transform, &mut Bubble)>,
time: Res<Time>,
) {
for (entity, mut transform, mut bubble) in bubbles.iter_mut() {
if bubble.timer.tick(time.delta()).just_finished() {
commands.entity(entity).despawn();
}
transform.translation.y += time.delta_seconds() * 100.0;
}
}
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();
}
}
}
}
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
fn change_reflection_type(
mut commands: Commands,
light_probe_query: Query<Entity, With<LightProbe>>,
camera_query: Query<Entity, With<Camera3d>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
cubemaps: Res<Cubemaps>,
) {
// Only do anything if space was pressed.
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
// Switch reflection mode.
app_status.reflection_mode =
ReflectionMode::try_from((app_status.reflection_mode as u32 + 1) % 3).unwrap();
// Add or remove the light probe.
for light_probe in light_probe_query.iter() {
commands.entity(light_probe).despawn();
}
match app_status.reflection_mode {
ReflectionMode::None | ReflectionMode::EnvironmentMap => {}
ReflectionMode::ReflectionProbe => spawn_reflection_probe(&mut commands, &cubemaps),
}
// Add or remove the environment map from the camera.
for camera in camera_query.iter() {
match app_status.reflection_mode {
ReflectionMode::None => {
commands.entity(camera).remove::<EnvironmentMapLight>();
}
ReflectionMode::EnvironmentMap | ReflectionMode::ReflectionProbe => {
commands
.entity(camera)
.insert(create_camera_environment_map_light(&cubemaps));
}
}
}
}
pub fn add<M>(
&mut self,
command: impl EntityCommand<M>
) -> &mut EntityCommands<'_>where
M: 'static,
pub fn add<M>(
&mut self,
command: impl EntityCommand<M>
) -> &mut EntityCommands<'_>where
M: 'static,
Pushes an EntityCommand
to the queue, which will get executed for the current Entity
.
§Examples
commands
.spawn_empty()
// Closures with this signature implement `EntityCommand`.
.add(|entity: EntityWorldMut| {
println!("Executed an EntityCommand for {:?}", entity.id());
});
pub fn retain<T>(&mut self) -> &mut EntityCommands<'_>where
T: Bundle,
pub fn retain<T>(&mut self) -> &mut EntityCommands<'_>where
T: Bundle,
Removes all components except the given Bundle
from the entity.
This can also be used to remove all the components from the entity by passing it an empty Bundle.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can retain a pre-defined Bundle of components,
// with this removing only the Defense component
.retain::<CombatBundle>()
// You can also retain only a single component
.retain::<Health>()
// And you can remove all the components by passing in an empty Bundle
.retain::<()>();
}
pub fn log_components(&mut self)
pub fn log_components(&mut self)
Logs the components of the entity at the info level.
§Panics
The command will panic when applied if the associated entity does not exist.
Trait Implementations§
§impl BuildChildren for EntityCommands<'_>
impl BuildChildren for EntityCommands<'_>
§fn with_children(
&mut self,
spawn_children: impl FnOnce(&mut ChildBuilder<'_>)
) -> &mut EntityCommands<'_>
fn with_children( &mut self, spawn_children: impl FnOnce(&mut ChildBuilder<'_>) ) -> &mut EntityCommands<'_>
ChildBuilder
.§fn push_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn push_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
§fn insert_children(
&mut self,
index: usize,
children: &[Entity]
) -> &mut EntityCommands<'_>
fn insert_children( &mut self, index: usize, children: &[Entity] ) -> &mut EntityCommands<'_>
§fn remove_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn remove_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
§fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'_>
fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'_>
§fn clear_children(&mut self) -> &mut EntityCommands<'_>
fn clear_children(&mut self) -> &mut EntityCommands<'_>
Children
component will be removed if it exists, otherwise this does nothing.§fn replace_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn replace_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
§fn set_parent(&mut self, parent: Entity) -> &mut EntityCommands<'_>
fn set_parent(&mut self, parent: Entity) -> &mut EntityCommands<'_>
§fn remove_parent(&mut self) -> &mut EntityCommands<'_>
fn remove_parent(&mut self) -> &mut EntityCommands<'_>
§impl BuildChildrenTransformExt for EntityCommands<'_>
impl BuildChildrenTransformExt for EntityCommands<'_>
§fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform
. Read more§fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform
to be equal to its current GlobalTransform
. Read more§impl DespawnRecursiveExt for EntityCommands<'_>
impl DespawnRecursiveExt for EntityCommands<'_>
§fn despawn_recursive(self)
fn despawn_recursive(self)
Despawns the provided entity and its children.
§fn despawn_descendants(&mut self) -> &mut EntityCommands<'_>
fn despawn_descendants(&mut self) -> &mut EntityCommands<'_>
§impl ReflectCommandExt for EntityCommands<'_>
impl ReflectCommandExt for EntityCommands<'_>
§fn insert_reflect(
&mut self,
component: Box<dyn Reflect>
) -> &mut EntityCommands<'_>
fn insert_reflect( &mut self, component: Box<dyn Reflect> ) -> &mut EntityCommands<'_>
AppTypeRegistry
. Read more§fn insert_reflect_with_registry<T>(
&mut self,
component: Box<dyn Reflect>
) -> &mut EntityCommands<'_>
fn insert_reflect_with_registry<T>( &mut self, component: Box<dyn Reflect> ) -> &mut EntityCommands<'_>
insert_reflect
, but using the T
resource as type registry instead of
AppTypeRegistry
. Read more§fn remove_reflect(
&mut self,
component_type_path: impl Into<Cow<'static, str>>
) -> &mut EntityCommands<'_>
fn remove_reflect( &mut self, component_type_path: impl Into<Cow<'static, str>> ) -> &mut EntityCommands<'_>
AppTypeRegistry
. Read more§fn remove_reflect_with_registry<T>(
&mut self,
component_type_name: impl Into<Cow<'static, str>>
) -> &mut EntityCommands<'_>
fn remove_reflect_with_registry<T>( &mut self, component_type_name: impl Into<Cow<'static, str>> ) -> &mut EntityCommands<'_>
Auto Trait Implementations§
impl<'a> RefUnwindSafe for EntityCommands<'a>
impl<'a> Send for EntityCommands<'a>
impl<'a> Sync for EntityCommands<'a>
impl<'a> Unpin for EntityCommands<'a>
impl<'a> !UnwindSafe for EntityCommands<'a>
Blanket Implementations§
§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
§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
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§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
.§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
.§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.§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.