code
stringlengths
40
729k
docstring
stringlengths
22
46.3k
func_name
stringlengths
1
97
language
stringclasses
1 value
repo
stringlengths
6
48
path
stringlengths
8
176
url
stringlengths
47
228
license
stringclasses
7 values
fn size(&self) -> Vec2 { let arena_height = TOP_WALL - BOTTOM_WALL; let arena_width = RIGHT_WALL - LEFT_WALL; // Make sure we haven't messed up our constants assert!(arena_height > 0.0); assert!(arena_width > 0.0); match self { WallLocation::Left | WallLocation::Right => { Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS) } WallLocation::Bottom | WallLocation::Top => { Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS) } } }
(x, y) dimensions of the wall, used in `transform.scale()`
size
rust
bevyengine/bevy
examples/games/breakout.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/breakout.rs
Apache-2.0
fn selection( mut timer: ResMut<SelectionTimer>, mut contributor_selection: ResMut<ContributorSelection>, contributor_root: Single<Entity, (With<ContributorDisplay>, With<Text>)>, mut query: Query<(&Contributor, &mut Sprite, &mut Transform)>, mut writer: TextUiWriter, time: Res<Time>, ) { if !timer.0.tick(time.delta()).just_finished() { return; } // Deselect the previous contributor let entity = contributor_selection.order[contributor_selection.idx]; if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) { deselect(&mut sprite, contributor, &mut transform); } // Select the next contributor if (contributor_selection.idx + 1) < contributor_selection.order.len() { contributor_selection.idx += 1; } else { contributor_selection.idx = 0; } let entity = contributor_selection.order[contributor_selection.idx]; if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) { let entity = *contributor_root; select( &mut sprite, contributor, &mut transform, entity, &mut writer, ); } }
Finds the next contributor to display and selects the entity
selection
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn select( sprite: &mut Sprite, contributor: &Contributor, transform: &mut Transform, entity: Entity, writer: &mut TextUiWriter, ) { sprite.color = SELECTED.with_hue(contributor.hue).into(); transform.translation.z += SELECTED_Z_OFFSET; writer.text(entity, 0).clone_from(&contributor.name); *writer.text(entity, 1) = format!( "\n{} commit{}", contributor.num_commits, if contributor.num_commits > 1 { "s" } else { "" } ); writer.color(entity, 0).0 = sprite.color; }
Change the tint color to the "selected" color, bring the object to the front and display the name.
select
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn deselect(sprite: &mut Sprite, contributor: &Contributor, transform: &mut Transform) { sprite.color = DESELECTED.with_hue(contributor.hue).into(); transform.translation.z -= SELECTED_Z_OFFSET; }
Change the tint color to the "deselected" color and push the object to the back.
deselect
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn gravity(time: Res<Time>, mut velocity_query: Query<&mut Velocity>) { let delta = time.delta_secs(); for mut velocity in &mut velocity_query { velocity.translation.y -= GRAVITY * delta; } }
Applies gravity to all entities with a velocity.
gravity
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn collisions( window: Query<&Window>, mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>, mut rng: ResMut<SharedRng>, ) { let Ok(window) = window.single() else { return; }; let window_size = window.size(); let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.); // The maximum height the birbs should try to reach is one birb below the top of the window. let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0); let min_bounce_height = max_bounce_height * 0.4; for (mut velocity, mut transform) in &mut query { // Clamp the translation to not go out of the bounds if transform.translation.y < collision_area.min.y { transform.translation.y = collision_area.min.y; // How high this birb will bounce. let bounce_height = rng.gen_range(min_bounce_height..=max_bounce_height); // Apply the velocity that would bounce the birb up to bounce_height. velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt(); } // Birbs might hit the ceiling if the window is resized. // If they do, bounce them. if transform.translation.y > collision_area.max.y { transform.translation.y = collision_area.max.y; velocity.translation.y *= -1.0; } // On side walls flip the horizontal velocity if transform.translation.x < collision_area.min.x { transform.translation.x = collision_area.min.x; velocity.translation.x *= -1.0; velocity.rotation *= -1.0; } if transform.translation.x > collision_area.max.x { transform.translation.x = collision_area.max.x; velocity.translation.x *= -1.0; velocity.rotation *= -1.0; } } }
Checks for collisions of contributor-birbs. On collision with left-or-right wall it resets the horizontal velocity. On collision with the ground it applies an upwards force.
collisions
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn movement(time: Res<Time>, mut query: Query<(&Velocity, &mut Transform)>) { let delta = time.delta_secs(); for (velocity, mut transform) in &mut query { transform.translation += delta * velocity.translation; transform.rotate_z(velocity.rotation * delta); } }
Apply velocity to positions and rotations.
movement
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn contributors_or_fallback() -> Contributors { let get_default = || { CONTRIBUTORS_LIST .iter() .cycle() .take(1000) .map(|name| (name.to_string(), 1)) .collect() }; if cfg!(feature = "bevy_ci_testing") { return get_default(); } contributors().unwrap_or_else(|_| get_default()) }
Get the contributors list, or fall back to a default value if it's unavailable or we're in CI
contributors_or_fallback
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn name_to_hue(s: &str) -> f32 { let mut hasher = DefaultHasher::new(); s.hash(&mut hasher); hasher.finish() as f32 / u64::MAX as f32 * 360. }
Give each unique contributor name a particular hue that is stable between runs.
name_to_hue
rust
bevyengine/bevy
examples/games/contributors.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/contributors.rs
Apache-2.0
fn get_cursor_world_pos( mut cursor_world_pos: ResMut<CursorWorldPos>, primary_window: Single<&Window, With<PrimaryWindow>>, q_camera: Single<(&Camera, &GlobalTransform)>, ) { let (main_camera, main_camera_transform) = *q_camera; // Get the cursor position in the world cursor_world_pos.0 = primary_window.cursor_position().and_then(|cursor_pos| { main_camera .viewport_to_world_2d(main_camera_transform, cursor_pos) .ok() }); }
Project the cursor into the world coordinates and store it in a resource for easy use
get_cursor_world_pos
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
fn update_cursor_hit_test( cursor_world_pos: Res<CursorWorldPos>, mut primary_window: Single<&mut Window, With<PrimaryWindow>>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { // If the window has decorations (e.g. a border) then it should be clickable if primary_window.decorations { primary_window.cursor_options.hit_test = true; return; } // If the cursor is not within the window we don't need to update whether the window is clickable or not let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // If the cursor is within the radius of the Bevy logo make the window clickable otherwise the window is not clickable primary_window.cursor_options.hit_test = bevy_logo_transform .translation .truncate() .distance(cursor_world_pos) < BEVY_LOGO_RADIUS; }
Update whether the window is clickable or not
update_cursor_hit_test
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
fn start_drag( mut commands: Commands, cursor_world_pos: Res<CursorWorldPos>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { // If the cursor is not within the primary window skip this system let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // Get the offset from the cursor to the Bevy logo sprite let drag_offset = bevy_logo_transform.translation.truncate() - cursor_world_pos; // If the cursor is within the Bevy logo radius start the drag operation and remember the offset of the cursor from the origin if drag_offset.length() < BEVY_LOGO_RADIUS { commands.insert_resource(DragOperation(drag_offset)); } }
Start the drag operation and record the offset we started dragging from
start_drag
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
fn quit( cursor_world_pos: Res<CursorWorldPos>, mut app_exit: EventWriter<AppExit>, bevy_logo_transform: Single<&Transform, With<BevyLogo>>, ) { // If the cursor is not within the primary window skip this system let Some(cursor_world_pos) = cursor_world_pos.0 else { return; }; // If the cursor is within the Bevy logo radius send the [`AppExit`] event to quit the app if bevy_logo_transform .translation .truncate() .distance(cursor_world_pos) < BEVY_LOGO_RADIUS { app_exit.write(AppExit::Success); } }
Quit when the user right clicks the Bevy logo
quit
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
fn toggle_transparency( mut commands: Commands, mut window_transparency: ResMut<WindowTransparency>, mut q_instructions_text: Query<&mut Visibility, With<InstructionsText>>, mut primary_window: Single<&mut Window, With<PrimaryWindow>>, ) { // Toggle the window transparency resource window_transparency.0 = !window_transparency.0; // Show or hide the instructions text for mut visibility in &mut q_instructions_text { *visibility = if window_transparency.0 { Visibility::Hidden } else { Visibility::Visible }; } // Remove the primary window's decorations (e.g. borders), make it always on top of other desktop windows, and set the clear color to transparent // only if window transparency is enabled let clear_color; ( primary_window.decorations, primary_window.window_level, clear_color, ) = if window_transparency.0 { (false, WindowLevel::AlwaysOnTop, Color::NONE) } else { (true, WindowLevel::Normal, WINDOW_CLEAR_COLOR) }; // Set the clear color commands.insert_resource(ClearColor(clear_color)); }
Enable transparency for the window and make it on top
toggle_transparency
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
fn move_pupils(time: Res<Time>, mut q_pupils: Query<(&mut Pupil, &mut Transform)>) { for (mut pupil, mut transform) in &mut q_pupils { // The wiggle radius is how much the pupil can move within the eye let wiggle_radius = pupil.eye_radius - pupil.pupil_radius; // Store the Z component let z = transform.translation.z; // Truncate the Z component to make the calculations be on [`Vec2`] let mut translation = transform.translation.truncate(); // Decay the pupil velocity pupil.velocity *= ops::powf(0.04f32, time.delta_secs()); // Move the pupil translation += pupil.velocity * time.delta_secs(); // If the pupil hit the outside border of the eye, limit the translation to be within the wiggle radius and invert the velocity. // This is not physically accurate but it's good enough for the googly eyes effect. if translation.length() > wiggle_radius { translation = translation.normalize() * wiggle_radius; // Invert and decrease the velocity of the pupil when it bounces pupil.velocity *= -0.75; } // Update the entity transform with the new translation after reading the Z component transform.translation = translation.extend(z); } }
Move the pupils and bounce them around
move_pupils
rust
bevyengine/bevy
examples/games/desk_toy.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/desk_toy.rs
Apache-2.0
pub fn add_schedule(mut self, label: impl ScheduleLabel) -> SteppingPlugin { self.schedule_labels.push(label.intern()); self }
add a schedule to be stepped when stepping is enabled
add_schedule
rust
bevyengine/bevy
examples/games/stepping.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/stepping.rs
Apache-2.0
pub fn at(self, left: Val, top: Val) -> SteppingPlugin { SteppingPlugin { top, left, ..self } }
Set the location of the stepping UI when activated
at
rust
bevyengine/bevy
examples/games/stepping.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/stepping.rs
Apache-2.0
fn build_ui( mut commands: Commands, asset_server: Res<AssetServer>, schedules: Res<Schedules>, mut stepping: ResMut<Stepping>, mut state: ResMut<State>, ) { let mut text_spans = Vec::new(); let mut always_run = Vec::new(); let Ok(schedule_order) = stepping.schedules() else { return; }; // go through the stepping schedules and construct a list of systems for // each label for label in schedule_order { let schedule = schedules.get(*label).unwrap(); text_spans.push(( TextSpan(format!("{label:?}\n")), TextFont { font: asset_server.load(FONT_BOLD), ..default() }, TextColor(FONT_COLOR), )); // grab the list of systems in the schedule, in the order the // single-threaded executor would run them. let Ok(systems) = schedule.systems() else { return; }; for (node_id, system) in systems { // skip bevy default systems; we don't want to step those if system.name().starts_with("bevy") { always_run.push((*label, node_id)); continue; } // Add an entry to our systems list so we can find where to draw // the cursor when the stepping cursor is at this system // we add plus 1 to account for the empty root span state.systems.push((*label, node_id, text_spans.len() + 1)); // Add a text section for displaying the cursor for this system text_spans.push(( TextSpan::new(" "), TextFont::default(), TextColor(FONT_COLOR), )); // add the name of the system to the ui text_spans.push(( TextSpan(format!("{}\n", system.name())), TextFont::default(), TextColor(FONT_COLOR), )); } } for (label, node) in always_run.drain(..) { stepping.always_run_node(label, node); } commands.spawn(( Text::default(), SteppingUi, Node { position_type: PositionType::Absolute, top: state.ui_top, left: state.ui_left, padding: UiRect::all(Val::Px(10.0)), ..default() }, BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)), Visibility::Hidden, Children::spawn(text_spans), )); }
Construct the stepping UI elements from the [`Schedules`] resource. This system may run multiple times before constructing the UI as all of the data may not be available on the first run of the system. This happens if one of the stepping schedules has not yet been run.
build_ui
rust
bevyengine/bevy
examples/games/stepping.rs
https://github.com/bevyengine/bevy/blob/master/examples/games/stepping.rs
Apache-2.0
pub fn main_ui_node() -> Node { Node { flex_direction: FlexDirection::Column, position_type: PositionType::Absolute, row_gap: Val::Px(6.0), left: Val::Px(10.0), bottom: Val::Px(10.0), ..default() } }
Returns a [`Node`] appropriate for the outer main UI node. This UI is in the bottom left corner and has flex column support
main_ui_node
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn spawn_option_button<T>( parent: &mut ChildSpawnerCommands, option_value: T, option_name: &str, is_selected: bool, is_first: bool, is_last: bool, ) where T: Clone + Send + Sync + 'static, { let (bg_color, fg_color) = if is_selected { (Color::WHITE, Color::BLACK) } else { (Color::BLACK, Color::WHITE) }; // Add the button node. parent .spawn(( Button, Node { border: BUTTON_BORDER.with_left(if is_first { Val::Px(1.0) } else { Val::Px(0.0) }), justify_content: JustifyContent::Center, align_items: AlignItems::Center, padding: BUTTON_PADDING, ..default() }, BUTTON_BORDER_COLOR, BorderRadius::ZERO .with_left(if is_first { BUTTON_BORDER_RADIUS_SIZE } else { Val::Px(0.0) }) .with_right(if is_last { BUTTON_BORDER_RADIUS_SIZE } else { Val::Px(0.0) }), BackgroundColor(bg_color), )) .insert(RadioButton) .insert(WidgetClickSender(option_value.clone())) .with_children(|parent| { spawn_ui_text(parent, option_name, fg_color) .insert(RadioButtonText) .insert(WidgetClickSender(option_value)); }); }
Spawns a single radio button that allows configuration of a setting. The type parameter specifies the value that will be packaged up and sent in a [`WidgetClickEvent`] when the radio button is clicked.
spawn_option_button
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn spawn_option_buttons<T>( parent: &mut ChildSpawnerCommands, title: &str, options: &[(T, &str)], ) where T: Clone + Send + Sync + 'static, { // Add the parent node for the row. parent .spawn(Node { align_items: AlignItems::Center, ..default() }) .with_children(|parent| { spawn_ui_text(parent, title, Color::BLACK).insert(Node { width: Val::Px(125.0), ..default() }); for (option_index, (option_value, option_name)) in options.iter().cloned().enumerate() { spawn_option_button( parent, option_value, option_name, option_index == 0, option_index == 0, option_index == options.len() - 1, ); } }); }
Spawns the buttons that allow configuration of a setting. The user may change the setting to any one of the labeled `options`. The value of the given type parameter will be packaged up and sent as a [`WidgetClickEvent`] when one of the radio buttons is clicked.
spawn_option_buttons
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn spawn_ui_text<'a>( parent: &'a mut ChildSpawnerCommands, label: &str, color: Color, ) -> EntityCommands<'a> { parent.spawn(( Text::new(label), TextFont { font_size: 18.0, ..default() }, TextColor(color), )) }
Spawns text for the UI. Returns the `EntityCommands`, which allow further customization of the text style.
spawn_ui_text
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn handle_ui_interactions<T>( mut interactions: Query< (&Interaction, &WidgetClickSender<T>), (With<Button>, With<RadioButton>), >, mut widget_click_events: EventWriter<WidgetClickEvent<T>>, ) where T: Clone + Send + Sync + 'static, { for (interaction, click_event) in interactions.iter_mut() { if *interaction == Interaction::Pressed { widget_click_events.write(WidgetClickEvent((**click_event).clone())); } } }
Checks for clicks on the radio buttons and sends `RadioButtonChangeEvent`s as necessary.
handle_ui_interactions
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn update_ui_radio_button(background_color: &mut BackgroundColor, selected: bool) { background_color.0 = if selected { Color::WHITE } else { Color::BLACK }; }
Updates the style of the button part of a radio button to reflect its selected status.
update_ui_radio_button
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
pub fn update_ui_radio_button_text(entity: Entity, writer: &mut TextUiWriter, selected: bool) { let text_color = if selected { Color::BLACK } else { Color::WHITE }; writer.for_each_color(entity, |mut color| { color.0 = text_color; }); }
Updates the color of the label of a radio button to reflect its selected status.
update_ui_radio_button_text
rust
bevyengine/bevy
examples/helpers/widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/helpers/widgets.rs
Apache-2.0
fn print_char_event_system(mut char_input_events: EventReader<KeyboardInput>) { for event in char_input_events.read() { // Only check for characters when the key is pressed. if !event.state.is_pressed() { continue; } if let Key::Character(character) = &event.logical_key { info!("{:?}: '{}'", event, character); } } }
This system prints out all char events as they come in.
print_char_event_system
rust
bevyengine/bevy
examples/input/char_input_events.rs
https://github.com/bevyengine/bevy/blob/master/examples/input/char_input_events.rs
Apache-2.0
fn print_keyboard_event_system(mut keyboard_input_events: EventReader<KeyboardInput>) { for event in keyboard_input_events.read() { info!("{:?}", event); } }
This system prints out all keyboard events as they come in
print_keyboard_event_system
rust
bevyengine/bevy
examples/input/keyboard_input_events.rs
https://github.com/bevyengine/bevy/blob/master/examples/input/keyboard_input_events.rs
Apache-2.0
fn keyboard_input_system(input: Res<ButtonInput<KeyCode>>) { let shift = input.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]); let ctrl = input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]); if ctrl && shift && input.just_pressed(KeyCode::KeyA) { info!("Just pressed Ctrl + Shift + A!"); } }
This system prints when `Ctrl + Shift + A` is pressed
keyboard_input_system
rust
bevyengine/bevy
examples/input/keyboard_modifiers.rs
https://github.com/bevyengine/bevy/blob/master/examples/input/keyboard_modifiers.rs
Apache-2.0
fn print_mouse_events_system( mut mouse_button_input_events: EventReader<MouseButtonInput>, mut mouse_motion_events: EventReader<MouseMotion>, mut cursor_moved_events: EventReader<CursorMoved>, mut mouse_wheel_events: EventReader<MouseWheel>, mut pinch_gesture_events: EventReader<PinchGesture>, mut rotation_gesture_events: EventReader<RotationGesture>, mut double_tap_gesture_events: EventReader<DoubleTapGesture>, ) { for event in mouse_button_input_events.read() { info!("{:?}", event); } for event in mouse_motion_events.read() { info!("{:?}", event); } for event in cursor_moved_events.read() { info!("{:?}", event); } for event in mouse_wheel_events.read() { info!("{:?}", event); } // This event will only fire on macOS for event in pinch_gesture_events.read() { info!("{:?}", event); } // This event will only fire on macOS for event in rotation_gesture_events.read() { info!("{:?}", event); } // This event will only fire on macOS for event in double_tap_gesture_events.read() { info!("{:?}", event); } }
This system prints out all mouse events as they come in
print_mouse_events_system
rust
bevyengine/bevy
examples/input/mouse_input_events.rs
https://github.com/bevyengine/bevy/blob/master/examples/input/mouse_input_events.rs
Apache-2.0
fn update_curve( control_points: Res<ControlPoints>, spline_mode: Res<SplineMode>, cycling_mode: Res<CyclingMode>, mut curve: ResMut<Curve>, ) { if !control_points.is_changed() && !spline_mode.is_changed() && !cycling_mode.is_changed() { return; } *curve = form_curve(&control_points, *spline_mode, *cycling_mode); }
This system is responsible for updating the [`Curve`] when the [control points] or active modes change. [control points]: ControlPoints
update_curve
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn draw_curve(curve: Res<Curve>, mut gizmos: Gizmos) { let Some(ref curve) = curve.0 else { return; }; // Scale resolution with curve length so it doesn't degrade as the length increases. let resolution = 100 * curve.segments().len(); gizmos.linestrip( curve.iter_positions(resolution).map(|pt| pt.extend(0.0)), Color::srgb(1.0, 1.0, 1.0), ); }
This system uses gizmos to draw the current [`Curve`] by breaking it up into a large number of line segments.
draw_curve
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn form_curve( control_points: &ControlPoints, spline_mode: SplineMode, cycling_mode: CyclingMode, ) -> Curve { let (points, tangents): (Vec<_>, Vec<_>) = control_points.points_and_tangents.iter().copied().unzip(); match spline_mode { SplineMode::Hermite => { let spline = CubicHermite::new(points, tangents); Curve(match cycling_mode { CyclingMode::NotCyclic => spline.to_curve().ok(), CyclingMode::Cyclic => spline.to_curve_cyclic().ok(), }) } SplineMode::Cardinal => { let spline = CubicCardinalSpline::new_catmull_rom(points); Curve(match cycling_mode { CyclingMode::NotCyclic => spline.to_curve().ok(), CyclingMode::Cyclic => spline.to_curve_cyclic().ok(), }) } SplineMode::B => { let spline = CubicBSpline::new(points); Curve(match cycling_mode { CyclingMode::NotCyclic => spline.to_curve().ok(), CyclingMode::Cyclic => spline.to_curve_cyclic().ok(), }) } } }
Helper function for generating a [`Curve`] from [control points] and selected modes. [control points]: ControlPoints
form_curve
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn handle_mouse_move( mut cursor_events: EventReader<CursorMoved>, mut mouse_position: ResMut<MousePosition>, ) { if let Some(cursor_event) = cursor_events.read().last() { mouse_position.0 = Some(cursor_event.position); } }
Update the current cursor position and track it in the [`MousePosition`] resource.
handle_mouse_move
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn handle_mouse_press( mut button_events: EventReader<MouseButtonInput>, mouse_position: Res<MousePosition>, mut edit_move: ResMut<MouseEditMove>, mut control_points: ResMut<ControlPoints>, camera: Single<(&Camera, &GlobalTransform)>, ) { let Some(mouse_pos) = mouse_position.0 else { return; }; // Handle click and drag behavior for button_event in button_events.read() { if button_event.button != MouseButton::Left { continue; } match button_event.state { ButtonState::Pressed => { if edit_move.start.is_some() { // If the edit move already has a start, press event should do nothing. continue; } // This press represents the start of the edit move. edit_move.start = Some(mouse_pos); } ButtonState::Released => { // Release is only meaningful if we started an edit move. let Some(start) = edit_move.start else { continue; }; let (camera, camera_transform) = *camera; // Convert the starting point and end point (current mouse pos) into world coords: let Ok(point) = camera.viewport_to_world_2d(camera_transform, start) else { continue; }; let Ok(end_point) = camera.viewport_to_world_2d(camera_transform, mouse_pos) else { continue; }; let tangent = end_point - point; // The start of the click-and-drag motion represents the point to add, // while the difference with the current position represents the tangent. control_points.points_and_tangents.push((point, tangent)); // Reset the edit move since we've consumed it. edit_move.start = None; } } } }
This system handles updating the [`MouseEditMove`] resource, orchestrating the logical part of the click-and-drag motion which actually creates new control points.
handle_mouse_press
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn draw_edit_move( edit_move: Res<MouseEditMove>, mouse_position: Res<MousePosition>, mut gizmos: Gizmos, camera: Single<(&Camera, &GlobalTransform)>, ) { let Some(start) = edit_move.start else { return; }; let Some(mouse_pos) = mouse_position.0 else { return; }; let (camera, camera_transform) = *camera; // Resources store data in viewport coordinates, so we need to convert to world coordinates // to display them: let Ok(start) = camera.viewport_to_world_2d(camera_transform, start) else { return; }; let Ok(end) = camera.viewport_to_world_2d(camera_transform, mouse_pos) else { return; }; gizmos.circle_2d(start, 10.0, Color::srgb(0.0, 1.0, 0.7)); gizmos.circle_2d(start, 7.0, Color::srgb(0.0, 1.0, 0.7)); gizmos.arrow_2d(start, end, Color::srgb(1.0, 0.0, 0.7)); }
This system handles drawing the "preview" control point based on the state of [`MouseEditMove`].
draw_edit_move
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn handle_keypress( keyboard: Res<ButtonInput<KeyCode>>, mut spline_mode: ResMut<SplineMode>, mut cycling_mode: ResMut<CyclingMode>, mut control_points: ResMut<ControlPoints>, ) { // S => change spline mode if keyboard.just_pressed(KeyCode::KeyS) { *spline_mode = match *spline_mode { SplineMode::Hermite => SplineMode::Cardinal, SplineMode::Cardinal => SplineMode::B, SplineMode::B => SplineMode::Hermite, } } // C => change cycling mode if keyboard.just_pressed(KeyCode::KeyC) { *cycling_mode = match *cycling_mode { CyclingMode::NotCyclic => CyclingMode::Cyclic, CyclingMode::Cyclic => CyclingMode::NotCyclic, } } // R => remove last control point if keyboard.just_pressed(KeyCode::KeyR) { control_points.points_and_tangents.pop(); } }
This system handles all keyboard commands.
handle_keypress
rust
bevyengine/bevy
examples/math/cubic_splines.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/cubic_splines.rs
Apache-2.0
fn list_all_shapes() -> Vec<Shape> { vec![ Shape::Cuboid, Shape::Sphere, Shape::Capsule, Shape::Cylinder, Shape::Tetrahedron, Shape::Triangle, ] }
Return a vector containing all implemented shapes
list_all_shapes
rust
bevyengine/bevy
examples/math/sampling_primitives.rs
https://github.com/bevyengine/bevy/blob/master/examples/math/sampling_primitives.rs
Apache-2.0
pub fn main() { let mut app = App::new(); app.add_plugins( DefaultPlugins .set(LogPlugin { // This will show some log events from Bevy to the native logger. level: Level::DEBUG, filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(), ..Default::default() }) .set(WindowPlugin { primary_window: Some(Window { resizable: false, mode: WindowMode::BorderlessFullscreen(MonitorSelection::Primary), // on iOS, gestures must be enabled. // This doesn't work on Android recognize_rotation_gesture: true, // Only has an effect on iOS prefers_home_indicator_hidden: true, // Only has an effect on iOS prefers_status_bar_hidden: true, // Only has an effect on iOS preferred_screen_edges_deferring_system_gestures: ScreenEdge::Bottom, ..default() }), ..default() }), ) // Make the winit loop wait more aggressively when no user input is received // This can help reduce cpu usage on mobile devices .insert_resource(WinitSettings::mobile()) .add_systems(Startup, (setup_scene, setup_music)) .add_systems( Update, ( touch_camera, button_handler, // Only run the lifetime handler when an [`AudioSink`] component exists in the world. // This ensures we don't try to manage audio that hasn't been initialized yet. handle_lifetime.run_if(any_with_component::<AudioSink>), ), ) .run(); }
The entry point for the application. Is `pub` so that it can be used from `main.rs`.
main
rust
bevyengine/bevy
examples/mobile/src/lib.rs
https://github.com/bevyengine/bevy/blob/master/examples/mobile/src/lib.rs
Apache-2.0
fn spawn_player(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); commands.spawn(( Name::new("Player"), Sprite::from_image(asset_server.load("branding/icon.png")), Transform::from_scale(Vec3::splat(0.3)), AccumulatedInput::default(), Velocity::default(), PhysicalTranslation::default(), PreviousPhysicalTranslation::default(), )); }
Spawn the player sprite and a 2D camera.
spawn_player
rust
bevyengine/bevy
examples/movement/physics_in_fixed_timestep.rs
https://github.com/bevyengine/bevy/blob/master/examples/movement/physics_in_fixed_timestep.rs
Apache-2.0
fn spawn_text(mut commands: Commands) { commands .spawn(Node { position_type: PositionType::Absolute, bottom: Val::Px(12.0), left: Val::Px(12.0), ..default() }) .with_child(( Text::new("Move the player with WASD"), TextFont { font_size: 25.0, ..default() }, )); }
Spawn a bit of UI text to explain how to move the player.
spawn_text
rust
bevyengine/bevy
examples/movement/physics_in_fixed_timestep.rs
https://github.com/bevyengine/bevy/blob/master/examples/movement/physics_in_fixed_timestep.rs
Apache-2.0
fn handle_input( keyboard_input: Res<ButtonInput<KeyCode>>, mut query: Query<(&mut AccumulatedInput, &mut Velocity)>, ) { /// Since Bevy's default 2D camera setup is scaled such that /// one unit is one pixel, you can think of this as /// "How many pixels per second should the player move?" const SPEED: f32 = 210.0; for (mut input, mut velocity) in query.iter_mut() { if keyboard_input.pressed(KeyCode::KeyW) { input.y += 1.0; } if keyboard_input.pressed(KeyCode::KeyS) { input.y -= 1.0; } if keyboard_input.pressed(KeyCode::KeyA) { input.x -= 1.0; } if keyboard_input.pressed(KeyCode::KeyD) { input.x += 1.0; } // Need to normalize and scale because otherwise // diagonal movement would be faster than horizontal or vertical movement. // This effectively averages the accumulated input. velocity.0 = input.extend(0.0).normalize_or_zero() * SPEED; } }
Handle keyboard input and accumulate it in the `AccumulatedInput` component. There are many strategies for how to handle all the input that happened since the last fixed timestep. This is a very simple one: we just accumulate the input and average it out by normalizing it.
handle_input
rust
bevyengine/bevy
examples/movement/physics_in_fixed_timestep.rs
https://github.com/bevyengine/bevy/blob/master/examples/movement/physics_in_fixed_timestep.rs
Apache-2.0
fn advance_physics( fixed_time: Res<Time<Fixed>>, mut query: Query<( &mut PhysicalTranslation, &mut PreviousPhysicalTranslation, &mut AccumulatedInput, &Velocity, )>, ) { for ( mut current_physical_translation, mut previous_physical_translation, mut input, velocity, ) in query.iter_mut() { previous_physical_translation.0 = current_physical_translation.0; current_physical_translation.0 += velocity.0 * fixed_time.delta_secs(); // Reset the input accumulator, as we are currently consuming all input that happened since the last fixed timestep. input.0 = Vec2::ZERO; } }
Advance the physics simulation by one fixed timestep. This may run zero or multiple times per frame. Note that since this runs in `FixedUpdate`, `Res<Time>` would be `Res<Time<Fixed>>` automatically. We are being explicit here for clarity.
advance_physics
rust
bevyengine/bevy
examples/movement/physics_in_fixed_timestep.rs
https://github.com/bevyengine/bevy/blob/master/examples/movement/physics_in_fixed_timestep.rs
Apache-2.0
fn update_material_on<E: EntityEvent>( new_material: Handle<StandardMaterial>, ) -> impl Fn(On<E>, Query<&mut MeshMaterial3d<StandardMaterial>>) { // An observer closure that captures `new_material`. We do this to avoid needing to write four // versions of this observer, each triggered by a different event and with a different hardcoded // material. Instead, the event type is a generic, and the material is passed in. move |trigger, mut query| { if let Ok(mut material) = query.get_mut(trigger.target()) { material.0 = new_material.clone(); } } }
Returns an observer that updates the entity's material to the one specified.
update_material_on
rust
bevyengine/bevy
examples/picking/mesh_picking.rs
https://github.com/bevyengine/bevy/blob/master/examples/picking/mesh_picking.rs
Apache-2.0
fn draw_mesh_intersections(pointers: Query<&PointerInteraction>, mut gizmos: Gizmos) { for (point, normal) in pointers .iter() .filter_map(|interaction| interaction.get_nearest_hit()) .filter_map(|(_entity, hit)| hit.position.zip(hit.normal)) { gizmos.sphere(point, 0.05, RED_500); gizmos.arrow(point, point + normal.normalize() * 0.5, PINK_100); } }
A system that draws hit indicators for every pointer.
draw_mesh_intersections
rust
bevyengine/bevy
examples/picking/mesh_picking.rs
https://github.com/bevyengine/bevy/blob/master/examples/picking/mesh_picking.rs
Apache-2.0
fn rotate_on_drag(drag: On<Pointer<Drag>>, mut transforms: Query<&mut Transform>) { let mut transform = transforms.get_mut(drag.target()).unwrap(); transform.rotate_y(drag.delta.x * 0.02); transform.rotate_x(drag.delta.y * 0.02); }
An observer to rotate an entity when it is dragged
rotate_on_drag
rust
bevyengine/bevy
examples/picking/mesh_picking.rs
https://github.com/bevyengine/bevy/blob/master/examples/picking/mesh_picking.rs
Apache-2.0
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2d); let len = 128.0; let sprite_size = Vec2::splat(len / 2.0); commands .spawn((Transform::default(), Visibility::default())) .with_children(|commands| { for (anchor_index, anchor) in [ Anchor::TOP_LEFT, Anchor::TOP_CENTER, Anchor::TOP_RIGHT, Anchor::CENTER_LEFT, Anchor::CENTER, Anchor::CENTER_RIGHT, Anchor::BOTTOM_LEFT, Anchor::BOTTOM_CENTER, Anchor::BOTTOM_RIGHT, ] .iter() .enumerate() { let i = (anchor_index % 3) as f32; let j = (anchor_index / 3) as f32; // Spawn black square behind sprite to show anchor point commands .spawn(( Sprite::from_color(Color::BLACK, sprite_size), Transform::from_xyz(i * len - len, j * len - len, -1.0), Pickable::default(), )) .observe(recolor_on::<Pointer<Over>>(Color::srgb(0.0, 1.0, 1.0))) .observe(recolor_on::<Pointer<Out>>(Color::BLACK)) .observe(recolor_on::<Pointer<Press>>(Color::srgb(1.0, 1.0, 0.0))) .observe(recolor_on::<Pointer<Release>>(Color::srgb(0.0, 1.0, 1.0))); commands .spawn(( Sprite { image: asset_server.load("branding/bevy_bird_dark.png"), custom_size: Some(sprite_size), color: Color::srgb(1.0, 0.0, 0.0), ..default() }, anchor.to_owned(), // 3x3 grid of anchor examples by changing transform Transform::from_xyz(i * len - len, j * len - len, 0.0) .with_scale(Vec3::splat(1.0 + (i - 1.0) * 0.2)) .with_rotation(Quat::from_rotation_z((j - 1.0) * 0.2)), Pickable::default(), )) .observe(recolor_on::<Pointer<Over>>(Color::srgb(0.0, 1.0, 0.0))) .observe(recolor_on::<Pointer<Out>>(Color::srgb(1.0, 0.0, 0.0))) .observe(recolor_on::<Pointer<Press>>(Color::srgb(0.0, 0.0, 1.0))) .observe(recolor_on::<Pointer<Release>>(Color::srgb(0.0, 1.0, 0.0))); } }); }
Set up a scene that tests all sprite anchor types.
setup
rust
bevyengine/bevy
examples/picking/sprite_picking.rs
https://github.com/bevyengine/bevy/blob/master/examples/picking/sprite_picking.rs
Apache-2.0
fn main() { App::new() .add_plugins(DefaultPlugins) .register_type::<ComponentA>() .register_type::<ComponentB>() .register_type::<ResourceA>() .add_systems( Startup, (save_scene_system, load_scene_system, infotext_system), ) .add_systems(Update, (log_system, panic_on_fail)) .run(); }
The entry point of our Bevy app. Sets up default plugins, registers all necessary component/resource types for serialization/reflection, and runs the various systems in the correct schedule.
main
rust
bevyengine/bevy
examples/scene/scene.rs
https://github.com/bevyengine/bevy/blob/master/examples/scene/scene.rs
Apache-2.0
fn log_system( query: Query<(Entity, &ComponentA), Changed<ComponentA>>, res: Option<Res<ResourceA>>, ) { for (entity, component_a) in &query { info!(" Entity({})", entity.index()); info!( " ComponentA: {{ x: {} y: {} }}\n", component_a.x, component_a.y ); } if let Some(res) = res { if res.is_added() { info!(" New ResourceA: {{ score: {} }}\n", res.score); } } }
Logs changes made to `ComponentA` entities, and also checks whether `ResourceA` has been recently added. Any time a `ComponentA` is modified, that change will appear here. This system demonstrates how you might detect and handle scene updates at runtime.
log_system
rust
bevyengine/bevy
examples/scene/scene.rs
https://github.com/bevyengine/bevy/blob/master/examples/scene/scene.rs
Apache-2.0
fn save_scene_system(world: &mut World) { // Scenes can be created from any ECS World. // You can either create a new one for the scene or use the current World. // For demonstration purposes, we'll create a new one. let mut scene_world = World::new(); // The `TypeRegistry` resource contains information about all registered types (including components). // This is used to construct scenes, so we'll want to ensure that our previous type registrations // exist in this new scene world as well. // To do this, we can simply clone the `AppTypeRegistry` resource. let type_registry = world.resource::<AppTypeRegistry>().clone(); scene_world.insert_resource(type_registry); let mut component_b = ComponentB::from_world(world); component_b.value = "hello".to_string(); scene_world.spawn(( component_b, ComponentA { x: 1.0, y: 2.0 }, Transform::IDENTITY, Name::new("joe"), )); scene_world.spawn(ComponentA { x: 3.0, y: 4.0 }); scene_world.insert_resource(ResourceA { score: 1 }); // With our sample world ready to go, we can now create our scene using DynamicScene or DynamicSceneBuilder. // For simplicity, we will create our scene using DynamicScene: let scene = DynamicScene::from_world(&scene_world); // Scenes can be serialized like this: let type_registry = world.resource::<AppTypeRegistry>(); let type_registry = type_registry.read(); let serialized_scene = scene.serialize(&type_registry).unwrap(); // Showing the scene in the console info!("{}", serialized_scene); // Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system // as they are blocking. // // This can't work in Wasm as there is no filesystem access. #[cfg(not(target_arch = "wasm32"))] IoTaskPool::get() .spawn(async move { // Write the scene RON data to file File::create(format!("assets/{NEW_SCENE_FILE_PATH}")) .and_then(|mut file| file.write(serialized_scene.as_bytes())) .expect("Error while writing scene to file"); }) .detach(); }
Demonstrates how to create a new scene from scratch, populate it with data, and then serialize it to a file. The new file is written to `NEW_SCENE_FILE_PATH`. This system creates a fresh world, duplicates the type registry so that our custom component types are recognized, spawns some sample entities and resources, and then serializes the resulting dynamic scene.
save_scene_system
rust
bevyengine/bevy
examples/scene/scene.rs
https://github.com/bevyengine/bevy/blob/master/examples/scene/scene.rs
Apache-2.0
fn infotext_system(mut commands: Commands) { commands.spawn(Camera2d); commands.spawn(( Text::new("Nothing to see in this window! Check the console output!"), TextFont { font_size: 42.0, ..default() }, Node { align_self: AlignSelf::FlexEnd, ..default() }, )); }
Spawns a simple 2D camera and some text indicating that the user should check the console output for scene loading/saving messages. This system is only necessary for the info message in the UI.
infotext_system
rust
bevyengine/bevy
examples/scene/scene.rs
https://github.com/bevyengine/bevy/blob/master/examples/scene/scene.rs
Apache-2.0
fn panic_on_fail(scenes: Query<&DynamicSceneRoot>, asset_server: Res<AssetServer>) { for scene in &scenes { if let Some(LoadState::Failed(err)) = asset_server.get_load_state(&scene.0) { panic!("Failed to load scene. {}", err); } } }
To help with Bevy's automated testing, we want the example to close with an appropriate if the scene fails to load. This is most likely not something you want in your own app.
panic_on_fail
rust
bevyengine/bevy
examples/scene/scene.rs
https://github.com/bevyengine/bevy/blob/master/examples/scene/scene.rs
Apache-2.0
fn setup( mut commands: Commands, assets: Res<AssetServer>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<CustomMaterial>>, ) { // We will use this image as our external data for our material to sample from in the vertex shader let image = assets.load("branding/icon.png"); // Our single mesh handle that will be instanced let mesh_handle = meshes.add(Cuboid::from_size(Vec3::splat(0.01))); // Create the custom material with a reference to our texture // Automatic instancing works with any Material, including the `StandardMaterial`. // This custom material is used to demonstrate the optional `MeshTag` feature. let material_handle = materials.add(CustomMaterial { image: image.clone(), }); // We're hardcoding the image dimensions for simplicity let image_dims = UVec2::new(256, 256); let total_pixels = image_dims.x * image_dims.y; for index in 0..total_pixels { // Get x,y from index - x goes left to right, y goes top to bottom let x = index % image_dims.x; let y = index / image_dims.x; // Convert to centered world coordinates let world_x = (x as f32 - image_dims.x as f32 / 2.0) / 50.0; let world_y = -((y as f32 - image_dims.y as f32 / 2.0) / 50.0); // Still need negative for world space commands.spawn(( // For automatic instancing to take effect you need to // use the same mesh handle and material handle for each instance Mesh3d(mesh_handle.clone()), MeshMaterial3d(material_handle.clone()), // This is an optional component that can be used to help tie external data to a mesh instance MeshTag(index), Transform::from_xyz(world_x, world_y, 0.0), )); } // Camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 0.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
Sets up an instanced grid of cubes, where each cube is colored based on an image that is sampled in the vertex shader. The cubes are then animated in a spiral pattern. This example demonstrates one use of automatic instancing and how to use `MeshTag` to use external data in a custom material. For example, here we use the "index" of each cube to determine the texel coordinate to sample from the image in the shader.
setup
rust
bevyengine/bevy
examples/shader/automatic_instancing.rs
https://github.com/bevyengine/bevy/blob/master/examples/shader/automatic_instancing.rs
Apache-2.0
fn rotate(time: Res<Time>, mut query: Query<&mut Transform, With<Rotates>>) { for mut transform in &mut query { transform.rotate_x(0.55 * time.delta_secs()); transform.rotate_z(0.15 * time.delta_secs()); } }
Rotates any entity around the x and y axis
rotate
rust
bevyengine/bevy
examples/shader/custom_post_processing.rs
https://github.com/bevyengine/bevy/blob/master/examples/shader/custom_post_processing.rs
Apache-2.0
fn toggle_prepass_view( mut prepass_view: Local<u32>, keycode: Res<ButtonInput<KeyCode>>, material_handle: Single<&MeshMaterial3d<PrepassOutputMaterial>>, mut materials: ResMut<Assets<PrepassOutputMaterial>>, text: Single<Entity, With<Text>>, mut writer: TextUiWriter, ) { if keycode.just_pressed(KeyCode::Space) { *prepass_view = (*prepass_view + 1) % 4; let label = match *prepass_view { 0 => "transparent", 1 => "depth", 2 => "normals", 3 => "motion vectors", _ => unreachable!(), }; let text = *text; *writer.text(text, 1) = format!("Prepass Output: {label}\n"); writer.for_each_color(text, |mut color| { color.0 = Color::WHITE; }); let mat = materials.get_mut(*material_handle).unwrap(); mat.settings.show_depth = (*prepass_view == 1) as u32; mat.settings.show_normals = (*prepass_view == 2) as u32; mat.settings.show_motion_vectors = (*prepass_view == 3) as u32; } }
Every time you press space, it will cycle between transparent, depth and normals view
toggle_prepass_view
rust
bevyengine/bevy
examples/shader/shader_prepass.rs
https://github.com/bevyengine/bevy/blob/master/examples/shader/shader_prepass.rs
Apache-2.0
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) { // Build a custom triangle mesh with colors // We define a custom mesh because the examples only uses a limited // set of vertex attributes for simplicity let mesh = Mesh::new( PrimitiveTopology::TriangleList, RenderAssetUsages::default(), ) .with_inserted_indices(Indices::U32(vec![0, 1, 2])) .with_inserted_attribute( Mesh::ATTRIBUTE_POSITION, vec![ vec3(-0.5, -0.5, 0.0), vec3(0.5, -0.5, 0.0), vec3(0.0, 0.25, 0.0), ], ) .with_inserted_attribute( Mesh::ATTRIBUTE_COLOR, vec![ vec4(1.0, 0.0, 0.0, 1.0), vec4(0.0, 1.0, 0.0, 1.0), vec4(0.0, 0.0, 1.0, 1.0), ], ); // spawn 3 triangles to show that batching works for (x, y) in [-0.5, 0.0, 0.5].into_iter().zip([-0.25, 0.5, -0.25]) { // Spawn an entity with all the required components for it to be rendered with our custom pipeline commands.spawn(( // We use a marker component to identify the mesh that will be rendered // with our specialized pipeline CustomRenderedEntity, // We need to add the mesh handle to the entity Mesh3d(meshes.add(mesh.clone())), Transform::from_xyz(x, y, 0.0), )); } // Spawn the camera. commands.spawn(( Camera3d::default(), // Move the camera back a bit to see all the triangles Transform::from_xyz(0.0, 0.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
Spawns the objects in the scene.
setup
rust
bevyengine/bevy
examples/shader/specialized_mesh_pipeline.rs
https://github.com/bevyengine/bevy/blob/master/examples/shader/specialized_mesh_pipeline.rs
Apache-2.0
fn queue_custom_mesh_pipeline( pipeline_cache: Res<PipelineCache>, custom_mesh_pipeline: Res<CustomMeshPipeline>, (mut opaque_render_phases, opaque_draw_functions): ( ResMut<ViewBinnedRenderPhases<Opaque3d>>, Res<DrawFunctions<Opaque3d>>, ), mut specialized_mesh_pipelines: ResMut<SpecializedMeshPipelines<CustomMeshPipeline>>, views: Query<( &RenderVisibleEntities, &ExtractedView, &Msaa, Has<NoIndirectDrawing>, Has<OcclusionCulling>, )>, (render_meshes, render_mesh_instances): ( Res<RenderAssets<RenderMesh>>, Res<RenderMeshInstances>, ), param: StaticSystemParam<<MeshPipeline as GetBatchData>::Param>, mut phase_batched_instance_buffers: ResMut< PhaseBatchedInstanceBuffers<Opaque3d, <MeshPipeline as GetBatchData>::BufferData>, >, mut phase_indirect_parameters_buffers: ResMut<PhaseIndirectParametersBuffers<Opaque3d>>, mut change_tick: Local<Tick>, ) { let system_param_item = param.into_inner(); let UntypedPhaseBatchedInstanceBuffers { ref mut data_buffer, ref mut work_item_buffers, ref mut late_indexed_indirect_parameters_buffer, ref mut late_non_indexed_indirect_parameters_buffer, .. } = phase_batched_instance_buffers.buffers; // Get the id for our custom draw function let draw_function_id = opaque_draw_functions .read() .id::<DrawSpecializedPipelineCommands>(); // Render phases are per-view, so we need to iterate over all views so that // the entity appears in them. (In this example, we have only one view, but // it's good practice to loop over all views anyway.) for (view_visible_entities, view, msaa, no_indirect_drawing, gpu_occlusion_culling) in views.iter() { let Some(opaque_phase) = opaque_render_phases.get_mut(&view.retained_view_entity) else { continue; }; // Create *work item buffers* if necessary. Work item buffers store the // indices of meshes that are to be rendered when indirect drawing is // enabled. let work_item_buffer = gpu_preprocessing::get_or_create_work_item_buffer::<Opaque3d>( work_item_buffers, view.retained_view_entity, no_indirect_drawing, gpu_occlusion_culling, ); // Initialize those work item buffers in preparation for this new frame. gpu_preprocessing::init_work_item_buffers( work_item_buffer, late_indexed_indirect_parameters_buffer, late_non_indexed_indirect_parameters_buffer, ); // Create the key based on the view. In this case we only care about MSAA and HDR let view_key = MeshPipelineKey::from_msaa_samples(msaa.samples()) | MeshPipelineKey::from_hdr(view.hdr); // Set up a slot to hold information about the batch set we're going to // create. If there are any of our custom meshes in the scene, we'll // need this information in order for Bevy to kick off the rendering. let mut mesh_batch_set_info = None; // Find all the custom rendered entities that are visible from this // view. for &(render_entity, visible_entity) in view_visible_entities.get::<CustomRenderedEntity>().iter() { // Get the mesh instance let Some(mesh_instance) = render_mesh_instances.render_mesh_queue_data(visible_entity) else { continue; }; // Get the mesh data let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else { continue; }; // Specialize the key for the current mesh entity // For this example we only specialize based on the mesh topology // but you could have more complex keys and that's where you'd need to create those keys let mut mesh_key = view_key; mesh_key |= MeshPipelineKey::from_primitive_topology(mesh.primitive_topology()); // Initialize the batch set information if this was the first custom // mesh we saw. We'll need that information later to create the // batch set. if mesh_batch_set_info.is_none() { mesh_batch_set_info = Some(MeshBatchSetInfo { indirect_parameters_index: phase_indirect_parameters_buffers .buffers .allocate(mesh.indexed(), 1), is_indexed: mesh.indexed(), }); } let mesh_info = mesh_batch_set_info.unwrap(); // Allocate some input and output indices. We'll need these to // create the *work item* below. let Some(input_index) = MeshPipeline::get_binned_index(&system_param_item, visible_entity) else { continue; }; let output_index = data_buffer.add() as u32; // Finally, we can specialize the pipeline based on the key let pipeline_id = specialized_mesh_pipelines .specialize( &pipeline_cache, &custom_mesh_pipeline, mesh_key, &mesh.layout, ) // This should never with this example, but if your pipeline specialization // can fail you need to handle the error here .expect("Failed to specialize mesh pipeline"); // Bump the change tick so that Bevy is forced to rebuild the bin. let next_change_tick = change_tick.get() + 1; change_tick.set(next_change_tick); // Add the mesh with our specialized pipeline opaque_phase.add( Opaque3dBatchSetKey { draw_function: draw_function_id, pipeline: pipeline_id, material_bind_group_index: None, vertex_slab: default(), index_slab: None, lightmap_slab: None, }, // The asset ID is arbitrary; we simply use [`AssetId::invalid`], // but you can use anything you like. Note that the asset ID need // not be the ID of a [`Mesh`]. Opaque3dBinKey { asset_id: AssetId::<Mesh>::invalid().untyped(), }, (render_entity, visible_entity), mesh_instance.current_uniform_index, // This example supports batching, but if your pipeline doesn't // support it you can use `BinnedRenderPhaseType::UnbatchableMesh` BinnedRenderPhaseType::BatchableMesh, *change_tick, ); // Create a *work item*. A work item tells the Bevy renderer to // transform the mesh on GPU. work_item_buffer.push( mesh.indexed(), PreprocessWorkItem { input_index: input_index.into(), output_or_indirect_parameters_index: if no_indirect_drawing { output_index } else { mesh_info.indirect_parameters_index }, }, ); } // Now if there were any meshes, we need to add a command to the // indirect parameters buffer, so that the renderer will end up // enqueuing a command to draw the mesh. if let Some(mesh_info) = mesh_batch_set_info { phase_indirect_parameters_buffers .buffers .add_batch_set(mesh_info.is_indexed, mesh_info.indirect_parameters_index); } } }
A render-world system that enqueues the entity with custom rendering into the opaque render phases of each view.
queue_custom_mesh_pipeline
rust
bevyengine/bevy
examples/shader/specialized_mesh_pipeline.rs
https://github.com/bevyengine/bevy/blob/master/examples/shader/specialized_mesh_pipeline.rs
Apache-2.0
fn run_reenter<S: States>(transition: In<Option<StateTransitionEvent<S>>>, world: &mut World) { // We return early if no transition event happened. let Some(transition) = transition.0 else { return; }; // If we wanted to ignore identity transitions, // we'd compare `exited` and `entered` here, // and return if they were the same. // We check if we actually entered a state. // A [`None`] would indicate that the state was removed from the world. // This only happens in the case of [`SubStates`] and [`ComputedStates`]. let Some(entered) = transition.entered else { return; }; // If all conditions are valid, we run our custom schedule. let _ = world.try_run_schedule(OnReenter(entered)); // If you want to overwrite the default `OnEnter` behavior to act like re-enter, // you can do so by running the `OnEnter` schedule here. Note that you don't want // to run `OnEnter` when the default behavior does so. // ``` // if transition.entered != transition.exited { // return; // } // let _ = world.try_run_schedule(OnReenter(entered)); // ``` }
Schedule runner which checks conditions and if they're right runs out custom schedule.
run_reenter
rust
bevyengine/bevy
examples/state/custom_transitions.rs
https://github.com/bevyengine/bevy/blob/master/examples/state/custom_transitions.rs
Apache-2.0
fn main() { // `from_env` panics on the web #[cfg(not(target_arch = "wasm32"))] let args: Args = argh::from_env(); #[cfg(target_arch = "wasm32")] let args = Args::from_args(&[], &[]).unwrap(); warn!(include_str!("warning_string.txt")); let mut app = App::new(); app.add_plugins(( DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { present_mode: PresentMode::AutoNoVsync, resolution: WindowResolution::new(1920.0, 1080.0).with_scale_factor_override(1.0), ..default() }), ..default() }), FrameTimeDiagnosticsPlugin::default(), LogDiagnosticsPlugin::default(), )) .insert_resource(WinitSettings { focused_mode: UpdateMode::Continuous, unfocused_mode: UpdateMode::Continuous, }) .add_systems(Update, (button_system, set_text_colors_changed)); if !args.no_camera { app.add_systems(Startup, |mut commands: Commands| { commands.spawn(Camera2d); }); } if args.many_cameras { app.add_systems(Startup, setup_many_cameras); } else if args.grid { app.add_systems(Startup, setup_grid); } else { app.add_systems(Startup, setup_flex); } if args.relayout { app.add_systems(Update, |mut nodes: Query<&mut Node>| { nodes.iter_mut().for_each(|mut node| node.set_changed()); }); } if args.recompute_text { app.add_systems(Update, |mut text_query: Query<&mut Text>| { text_query .iter_mut() .for_each(|mut text| text.set_changed()); }); } if args.respawn { if args.grid { app.add_systems(Update, (despawn_ui, setup_grid).chain()); } else { app.add_systems(Update, (despawn_ui, setup_flex).chain()); } } app.insert_resource(args).run(); }
This example shows what happens when there is a lot of buttons on screen.
main
rust
bevyengine/bevy
examples/stress_tests/many_buttons.rs
https://github.com/bevyengine/bevy/blob/master/examples/stress_tests/many_buttons.rs
Apache-2.0
fn set_translation(translation: &mut Vec3, a: f32) { translation.x = ops::cos(a) * 32.0; translation.y = ops::sin(a) * 32.0; }
set translation based on the angle `a`
set_translation
rust
bevyengine/bevy
examples/stress_tests/transform_hierarchy.rs
https://github.com/bevyengine/bevy/blob/master/examples/stress_tests/transform_hierarchy.rs
Apache-2.0
fn spawn_tree( parent_map: &[usize], commands: &mut Commands, update_filter: &UpdateFilter, root_transform: Transform, ) -> InsertResult { // total count (# of nodes + root) let count = parent_map.len() + 1; #[derive(Default, Clone, Copy)] struct NodeInfo { child_count: u32, depth: u32, } // node index -> entity lookup list let mut ents: Vec<Entity> = Vec::with_capacity(count); let mut node_info: Vec<NodeInfo> = vec![default(); count]; for (i, &parent_idx) in parent_map.iter().enumerate() { // assert spawn order (parent must be processed before child) assert!(parent_idx <= i, "invalid spawn order"); node_info[parent_idx].child_count += 1; } // insert root ents.push(commands.spawn(root_transform).id()); let mut result = InsertResult::default(); let mut rng = rand::thread_rng(); // used to count through the number of children (used only for visual layout) let mut child_idx: Vec<u16> = vec![0; count]; // insert children for (current_idx, &parent_idx) in parent_map.iter().enumerate() { let current_idx = current_idx + 1; // separation factor to visually separate children (0..1) let sep = child_idx[parent_idx] as f32 / node_info[parent_idx].child_count as f32; child_idx[parent_idx] += 1; // calculate and set depth // this works because it's guaranteed that we have already iterated over the parent let depth = node_info[parent_idx].depth + 1; let info = &mut node_info[current_idx]; info.depth = depth; // update max depth of tree result.maximum_depth = result.maximum_depth.max(depth.try_into().unwrap()); // insert child let child_entity = { let mut cmd = commands.spawn_empty(); // check whether or not to update this node let update = (rng.r#gen::<f32>() <= update_filter.probability) && (depth >= update_filter.min_depth && depth <= update_filter.max_depth); if update { cmd.insert(UpdateValue(sep)); result.active_nodes += 1; } let transform = { let mut translation = Vec3::ZERO; // use the same placement fn as the `update` system // this way the entities won't be all at (0, 0, 0) when they don't have an `Update` component set_translation(&mut translation, sep); Transform::from_translation(translation) }; // only insert the components necessary for the transform propagation cmd.insert(transform); cmd.id() }; commands.entity(ents[parent_idx]).add_child(child_entity); ents.push(child_entity); } result.inserted_nodes = ents.len(); result }
spawns a tree defined by a parent map (excluding root) the parent map must be ordered (parent must exist before child)
spawn_tree
rust
bevyengine/bevy
examples/stress_tests/transform_hierarchy.rs
https://github.com/bevyengine/bevy/blob/master/examples/stress_tests/transform_hierarchy.rs
Apache-2.0
fn gen_tree(depth: u32, branch_width: u32) -> Vec<usize> { // calculate the total count of branches let mut count: usize = 0; for i in 0..(depth - 1) { count += TryInto::<usize>::try_into(branch_width.pow(i)).unwrap(); } // the tree is built using this pattern: // 0, 0, 0, ... 1, 1, 1, ... 2, 2, 2, ... (count - 1) (0..count) .flat_map(|i| std::iter::repeat_n(i, branch_width.try_into().unwrap())) .collect() }
generate a tree `depth` levels deep, where each node has `branch_width` children
gen_tree
rust
bevyengine/bevy
examples/stress_tests/transform_hierarchy.rs
https://github.com/bevyengine/bevy/blob/master/examples/stress_tests/transform_hierarchy.rs
Apache-2.0
fn gen_non_uniform_tree(max_depth: u32, max_branch_width: u32) -> Vec<usize> { let mut tree = Vec::new(); add_children_non_uniform(&mut tree, 0, max_depth, max_branch_width); tree }
generate a tree that has more nodes on one side that the other the deepest hierarchy path is `max_depth` and the widest branches have `max_branch_width` children
gen_non_uniform_tree
rust
bevyengine/bevy
examples/stress_tests/transform_hierarchy.rs
https://github.com/bevyengine/bevy/blob/master/examples/stress_tests/transform_hierarchy.rs
Apache-2.0
pub fn update_scroll_position( mut mouse_wheel_events: EventReader<MouseWheel>, hover_map: Res<HoverMap>, mut scrolled_node_query: Query<&mut ScrollPosition>, keyboard_input: Res<ButtonInput<KeyCode>>, ) { for mouse_wheel_event in mouse_wheel_events.read() { let (mut dx, mut dy) = match mouse_wheel_event.unit { MouseScrollUnit::Line => (mouse_wheel_event.x * 20., mouse_wheel_event.y * 20.), MouseScrollUnit::Pixel => (mouse_wheel_event.x, mouse_wheel_event.y), }; if keyboard_input.pressed(KeyCode::ShiftLeft) || keyboard_input.pressed(KeyCode::ShiftRight) { std::mem::swap(&mut dx, &mut dy); } for (_pointer, pointer_map) in hover_map.iter() { for (entity, _hit) in pointer_map.iter() { if let Ok(mut scroll_position) = scrolled_node_query.get_mut(*entity) { scroll_position.offset_x -= dx; scroll_position.offset_y -= dy; } } } } }
Updates the scroll position of scrollable nodes in response to mouse input
update_scroll_position
rust
bevyengine/bevy
examples/testbed/full_ui.rs
https://github.com/bevyengine/bevy/blob/master/examples/testbed/full_ui.rs
Apache-2.0
fn print_when_completed(time: Res<Time>, mut query: Query<&mut PrintOnCompletionTimer>) { for mut timer in &mut query { if timer.tick(time.delta()).just_finished() { info!("Entity timer just finished"); } } }
This system ticks the `Timer` on the entity with the `PrintOnCompletionTimer` component using bevy's `Time` resource to get the delta between each update.
print_when_completed
rust
bevyengine/bevy
examples/time/timers.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/timers.rs
Apache-2.0
fn countdown(time: Res<Time>, mut countdown: ResMut<Countdown>) { countdown.main_timer.tick(time.delta()); // The API encourages this kind of timer state checking (if you're only checking for one value) // Additionally, `is_finished()` would accomplish the same thing as `just_finished` due to the // timer being repeating, however this makes more sense visually. if countdown.percent_trigger.tick(time.delta()).just_finished() { if !countdown.main_timer.is_finished() { // Print the percent complete the main timer is. info!( "Timer is {:0.0}% complete!", countdown.main_timer.fraction() * 100.0 ); } else { // The timer has finished so we pause the percent output timer countdown.percent_trigger.pause(); info!("Paused percent trigger timer"); } } }
This system controls ticking the timer within the countdown resource and handling its state.
countdown
rust
bevyengine/bevy
examples/time/timers.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/timers.rs
Apache-2.0
fn move_real_time_sprites( mut sprite_query: Query<&mut Transform, (With<Sprite>, With<RealTime>)>, // `Real` time which is not scaled or paused time: Res<Time<Real>>, ) { for mut transform in sprite_query.iter_mut() { // move roughly half the screen in a `Real` second // when the time is scaled the speed is going to change // and the sprite will stay still the time is paused transform.translation.x = get_sprite_translation_x(time.elapsed_secs()); } }
Move sprites using `Real` (unscaled) time
move_real_time_sprites
rust
bevyengine/bevy
examples/time/virtual_time.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/virtual_time.rs
Apache-2.0
fn move_virtual_time_sprites( mut sprite_query: Query<&mut Transform, (With<Sprite>, With<VirtualTime>)>, // the default `Time` is either `Time<Virtual>` in regular systems // or `Time<Fixed>` in fixed timestep systems so `Time::delta()`, // `Time::elapsed()` will return the appropriate values either way time: Res<Time>, ) { for mut transform in sprite_query.iter_mut() { // move roughly half the screen in a `Virtual` second // when time is scaled using `Time<Virtual>::set_relative_speed` it's going // to move at a different pace and the sprite will stay still when time is // `Time<Virtual>::is_paused()` transform.translation.x = get_sprite_translation_x(time.elapsed_secs()); } }
Move sprites using `Virtual` (scaled) time
move_virtual_time_sprites
rust
bevyengine/bevy
examples/time/virtual_time.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/virtual_time.rs
Apache-2.0
fn change_time_speed<const DELTA: i8>(mut time: ResMut<Time<Virtual>>) { let time_speed = (time.relative_speed() + DELTA as f32) .round() .clamp(0.25, 5.); // set the speed of the virtual time to speed it up or slow it down time.set_relative_speed(time_speed); }
Update the speed of `Time<Virtual>.` by `DELTA`
change_time_speed
rust
bevyengine/bevy
examples/time/virtual_time.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/virtual_time.rs
Apache-2.0
fn update_real_time_info_text(time: Res<Time<Real>>, mut query: Query<&mut Text, With<RealTime>>) { for mut text in &mut query { **text = format!( "REAL TIME\nElapsed: {:.1}\nDelta: {:.5}\n", time.elapsed_secs(), time.delta_secs(), ); } }
Update the `Real` time info text
update_real_time_info_text
rust
bevyengine/bevy
examples/time/virtual_time.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/virtual_time.rs
Apache-2.0
fn update_virtual_time_info_text( time: Res<Time<Virtual>>, mut query: Query<&mut Text, With<VirtualTime>>, ) { for mut text in &mut query { **text = format!( "VIRTUAL TIME\nElapsed: {:.1}\nDelta: {:.5}\nSpeed: {:.2}", time.elapsed_secs(), time.delta_secs(), time.relative_speed() ); } }
Update the `Virtual` time info text
update_virtual_time_info_text
rust
bevyengine/bevy
examples/time/virtual_time.rs
https://github.com/bevyengine/bevy/blob/master/examples/time/virtual_time.rs
Apache-2.0
fn assign_clips( mut players: Query<&mut AnimationPlayer>, targets: Query<(Entity, &AnimationTarget)>, children: Query<&ChildOf>, scene_handle: Res<SceneHandle>, clips: Res<Assets<AnimationClip>>, gltf_assets: Res<Assets<Gltf>>, assets: Res<AssetServer>, mut graphs: ResMut<Assets<AnimationGraph>>, mut commands: Commands, mut setup: Local<bool>, ) { if scene_handle.is_loaded && !*setup { *setup = true; } else { return; } let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap(); let animations = &gltf.animations; if animations.is_empty() { return; } let count = animations.len(); let plural = if count == 1 { "" } else { "s" }; info!("Found {} animation{plural}", animations.len()); let names: Vec<_> = gltf.named_animations.keys().collect(); info!("Animation names: {names:?}"); // Map animation target IDs to entities. let animation_target_id_to_entity: HashMap<_, _> = targets .iter() .map(|(entity, target)| (target.id, entity)) .collect(); // Build up a list of all animation clips that belong to each player. A clip // is considered to belong to an animation player if all targets of the clip // refer to entities whose nearest ancestor player is that animation player. let mut player_to_graph: EntityHashMap<(AnimationGraph, Vec<AnimationNodeIndex>)> = EntityHashMap::default(); for (clip_id, clip) in clips.iter() { let mut ancestor_player = None; for target_id in clip.curves().keys() { // If the animation clip refers to entities that aren't present in // the scene, bail. let Some(&target) = animation_target_id_to_entity.get(target_id) else { continue; }; // Find the nearest ancestor animation player. let mut current = Some(target); while let Some(entity) = current { if players.contains(entity) { match ancestor_player { None => { // If we haven't found a player yet, record the one // we found. ancestor_player = Some(entity); } Some(ancestor) => { // If we have found a player, then make sure it's // the same player we located before. if ancestor != entity { // It's a different player. Bail. ancestor_player = None; break; } } } } // Go to the next parent. current = children.get(entity).ok().map(ChildOf::parent); } } let Some(ancestor_player) = ancestor_player else { warn!( "Unexpected animation hierarchy for animation clip {}; ignoring.", clip_id ); continue; }; let Some(clip_handle) = assets.get_id_handle(clip_id) else { warn!("Clip {} wasn't loaded.", clip_id); continue; }; let &mut (ref mut graph, ref mut clip_indices) = player_to_graph.entry(ancestor_player).or_default(); let node_index = graph.add_clip(clip_handle, 1.0, graph.root); clip_indices.push(node_index); } // Now that we've built up a list of all clips that belong to each player, // package them up into a `Clips` component, play the first such animation, // and add that component to the player. for (player_entity, (graph, clips)) in player_to_graph { let Ok(mut player) = players.get_mut(player_entity) else { warn!("Animation targets referenced a nonexistent player. This shouldn't happen."); continue; }; let graph = graphs.add(graph); let animations = Clips::new(clips); player.play(animations.current()).repeat(); commands .entity(player_entity) .insert(animations) .insert(AnimationGraphHandle(graph)); } }
Automatically assign [`AnimationClip`]s to [`AnimationPlayer`] and play them, if the clips refer to descendants of the animation player (which is the common case).
assign_clips
rust
bevyengine/bevy
examples/tools/scene_viewer/animation_plugin.rs
https://github.com/bevyengine/bevy/blob/master/examples/tools/scene_viewer/animation_plugin.rs
Apache-2.0
fn update_button_style2( mut buttons: Query< ( Has<Pressed>, &Hovered, Has<InteractionDisabled>, &mut BackgroundColor, &mut BorderColor, &Children, ), With<DemoButton>, >, mut removed_depressed: RemovedComponents<Pressed>, mut removed_disabled: RemovedComponents<InteractionDisabled>, mut text_query: Query<&mut Text>, ) { removed_depressed.read().for_each(|entity| { if let Ok((pressed, hovered, disabled, mut color, mut border_color, children)) = buttons.get_mut(entity) { let mut text = text_query.get_mut(children[0]).unwrap(); set_button_style( disabled, hovered.get(), pressed, &mut color, &mut border_color, &mut text, ); } }); removed_disabled.read().for_each(|entity| { if let Ok((pressed, hovered, disabled, mut color, mut border_color, children)) = buttons.get_mut(entity) { let mut text = text_query.get_mut(children[0]).unwrap(); set_button_style( disabled, hovered.get(), pressed, &mut color, &mut border_color, &mut text, ); } }); }
Supplementary system to detect removed marker components
update_button_style2
rust
bevyengine/bevy
examples/ui/core_widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/core_widgets.rs
Apache-2.0
fn update_widget_values( res: Res<DemoWidgetStates>, mut sliders: Query<Entity, With<DemoSlider>>, mut commands: Commands, ) { if res.is_changed() { for slider_ent in sliders.iter_mut() { commands .entity(slider_ent) .insert(SliderValue(res.slider_value)); } } }
Update the widget states based on the changing resource.
update_widget_values
rust
bevyengine/bevy
examples/ui/core_widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/core_widgets.rs
Apache-2.0
fn update_slider_style( sliders: Query< ( Entity, &SliderValue, &SliderRange, &Hovered, Has<InteractionDisabled>, ), ( Or<( Changed<SliderValue>, Changed<SliderRange>, Changed<Hovered>, Added<InteractionDisabled>, )>, With<DemoSlider>, ), >, children: Query<&Children>, mut thumbs: Query<(&mut Node, &mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>, ) { for (slider_ent, value, range, hovered, disabled) in sliders.iter() { for child in children.iter_descendants(slider_ent) { if let Ok((mut thumb_node, mut thumb_bg, is_thumb)) = thumbs.get_mut(child) { if is_thumb { thumb_node.left = Val::Percent(range.thumb_position(value.0) * 100.0); thumb_bg.0 = thumb_color(disabled, hovered.0); } } } } }
Update the visuals of the slider based on the slider state.
update_slider_style
rust
bevyengine/bevy
examples/ui/core_widgets.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/core_widgets.rs
Apache-2.0
fn update_widget_values( res: Res<DemoWidgetStates>, mut sliders: Query<Entity, With<DemoSlider>>, mut commands: Commands, ) { if res.is_changed() { for slider_ent in sliders.iter_mut() { commands .entity(slider_ent) .insert(SliderValue(res.slider_value)); } } }
Update the widget states based on the changing resource.
update_widget_values
rust
bevyengine/bevy
examples/ui/core_widgets_observers.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/core_widgets_observers.rs
Apache-2.0
fn item_rect(builder: &mut ChildSpawnerCommands, color: Srgba) { builder .spawn(( Node { display: Display::Grid, padding: UiRect::all(Val::Px(3.0)), ..default() }, BackgroundColor(BLACK.into()), )) .with_children(|builder| { builder.spawn((Node::default(), BackgroundColor(color.into()))); }); }
Create a colored rectangle node. The node has size as it is assumed that it will be spawned as a child of a Grid container with `AlignItems::Stretch` and `JustifyItems::Stretch` which will allow it to take its size from the size of the grid area it occupies.
item_rect
rust
bevyengine/bevy
examples/ui/grid.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/grid.rs
Apache-2.0
fn relative_cursor_position_system( relative_cursor_position: Single<&RelativeCursorPosition>, output_query: Single<(&mut Text, &mut TextColor)>, ) { let (mut output, mut text_color) = output_query.into_inner(); **output = 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() }; text_color.0 = if relative_cursor_position.cursor_over() { Color::srgb(0.1, 0.9, 0.1) } else { Color::srgb(0.9, 0.1, 0.1) }; }
This systems polls the relative cursor position and displays its value in a text component.
relative_cursor_position_system
rust
bevyengine/bevy
examples/ui/relative_cursor_position.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/relative_cursor_position.rs
Apache-2.0
pub fn update_scroll_position( mut mouse_wheel_events: EventReader<MouseWheel>, hover_map: Res<HoverMap>, mut scrolled_node_query: Query<&mut ScrollPosition>, keyboard_input: Res<ButtonInput<KeyCode>>, ) { for mouse_wheel_event in mouse_wheel_events.read() { let (mut dx, mut dy) = match mouse_wheel_event.unit { MouseScrollUnit::Line => ( mouse_wheel_event.x * LINE_HEIGHT, mouse_wheel_event.y * LINE_HEIGHT, ), MouseScrollUnit::Pixel => (mouse_wheel_event.x, mouse_wheel_event.y), }; if keyboard_input.pressed(KeyCode::ControlLeft) || keyboard_input.pressed(KeyCode::ControlRight) { std::mem::swap(&mut dx, &mut dy); } for (_pointer, pointer_map) in hover_map.iter() { for (entity, _hit) in pointer_map.iter() { if let Ok(mut scroll_position) = scrolled_node_query.get_mut(*entity) { scroll_position.offset_x -= dx; scroll_position.offset_y -= dy; } } } } }
Updates the scroll position of scrollable nodes in response to mouse input
update_scroll_position
rust
bevyengine/bevy
examples/ui/scroll.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/scroll.rs
Apache-2.0
fn change_scaling(input: Res<ButtonInput<KeyCode>>, mut ui_scale: ResMut<TargetScale>) { if input.just_pressed(KeyCode::ArrowUp) { let scale = (ui_scale.target_scale * 2.0).min(8.); ui_scale.set_scale(scale); info!("Scaling up! Scale: {}", ui_scale.target_scale); } if input.just_pressed(KeyCode::ArrowDown) { let scale = (ui_scale.target_scale / 2.0).max(1. / 8.); ui_scale.set_scale(scale); info!("Scaling down! Scale: {}", ui_scale.target_scale); } }
System that changes the scale of the ui when pressing up or down on the keyboard.
change_scaling
rust
bevyengine/bevy
examples/ui/ui_scaling.rs
https://github.com/bevyengine/bevy/blob/master/examples/ui/ui_scaling.rs
Apache-2.0
fn text_color_on_hover<T: Debug + Clone + Reflect>( color: Color, ) -> impl FnMut(On<Pointer<T>>, Query<&mut TextColor>, Query<&Children>) { move |mut trigger: On<Pointer<T>>, mut text_color: Query<&mut TextColor>, children: Query<&Children>| { let Ok(children) = children.get(trigger.original_target()) else { return; }; trigger.propagate(false); // find the text among children and change its color for child in children.iter() { if let Ok(mut col) = text_color.get_mut(child) { col.0 = color; } } } }
helper function to reduce code duplication when generating almost identical observers for the hover text color change effect
text_color_on_hover
rust
bevyengine/bevy
examples/usages/context_menu.rs
https://github.com/bevyengine/bevy/blob/master/examples/usages/context_menu.rs
Apache-2.0
fn execute_animation(time: Res<Time>, mut query: Query<(&mut AnimationConfig, &mut CursorIcon)>) { for (mut config, mut cursor_icon) in &mut query { if let CursorIcon::Custom(CustomCursor::Image(ref mut image)) = *cursor_icon { config.frame_timer.tick(time.delta()); if config.frame_timer.is_finished() { if let Some(atlas) = image.texture_atlas.as_mut() { atlas.index += config.increment; if atlas.index > config.last_sprite_index { atlas.index = config.first_sprite_index; } config.frame_timer = AnimationConfig::timer_from_fps(config.fps); } } } } }
This system loops through all the sprites in the [`CursorIcon`]'s [`TextureAtlas`], from [`AnimationConfig`]'s `first_sprite_index` to `last_sprite_index`.
execute_animation
rust
bevyengine/bevy
examples/window/custom_cursor_image.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/custom_cursor_image.rs
Apache-2.0
fn cycle_rect(input: Res<ButtonInput<KeyCode>>, mut query: Query<&mut CursorIcon, With<Window>>) { if !input.just_pressed(KeyCode::KeyC) { return; } const RECT_SIZE: u32 = 32; // half the size of a tile in the texture atlas const SECTIONS: [Option<URect>; 5] = [ Some(URect { min: UVec2::ZERO, max: UVec2::splat(RECT_SIZE), }), Some(URect { min: UVec2::new(RECT_SIZE, 0), max: UVec2::new(2 * RECT_SIZE, RECT_SIZE), }), Some(URect { min: UVec2::new(0, RECT_SIZE), max: UVec2::new(RECT_SIZE, 2 * RECT_SIZE), }), Some(URect { min: UVec2::new(RECT_SIZE, RECT_SIZE), max: UVec2::splat(2 * RECT_SIZE), }), None, // reset to None ]; for mut cursor_icon in &mut query { if let CursorIcon::Custom(CustomCursor::Image(ref mut image)) = *cursor_icon { let next_rect = SECTIONS .iter() .cycle() .skip_while(|&&corner| corner != image.rect) .nth(1) // move to the next element .unwrap_or(&None); image.rect = *next_rect; } } }
This system alternates the [`CursorIcon`]'s `rect` field between `None` and 4 sections/rectangles of the cursor's image.
cycle_rect
rust
bevyengine/bevy
examples/window/custom_cursor_image.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/custom_cursor_image.rs
Apache-2.0
fn update_winit( mode: Res<ExampleMode>, mut winit_config: ResMut<WinitSettings>, event_loop_proxy: Res<EventLoopProxyWrapper<WakeUp>>, mut redraw_request_events: EventWriter<RequestRedraw>, ) { use ExampleMode::*; *winit_config = match *mode { Game => { // In the default `WinitSettings::game()` mode: // * When focused: the event loop runs as fast as possible // * When not focused: the app will update when the window is directly interacted with // (e.g. the mouse hovers over a visible part of the out of focus window), a // [`RequestRedraw`] event is received, or one sixtieth of a second has passed // without the app updating (60 Hz refresh rate max). WinitSettings::game() } Application => { // While in `WinitSettings::desktop_app()` mode: // * When focused: the app will update any time a winit event (e.g. the window is // moved/resized, the mouse moves, a button is pressed, etc.), a [`RequestRedraw`] // event is received, or after 5 seconds if the app has not updated. // * When not focused: the app will update when the window is directly interacted with // (e.g. the mouse hovers over a visible part of the out of focus window), a // [`RequestRedraw`] event is received, or one minute has passed without the app // updating. WinitSettings::desktop_app() } ApplicationWithRequestRedraw => { // Sending a `RequestRedraw` event is useful when you want the app to update the next // frame regardless of any user input. For example, your application might use // `WinitSettings::desktop_app()` to reduce power use, but UI animations need to play even // when there are no inputs, so you send redraw requests while the animation is playing. // Note that in this example the RequestRedraw winit event will make the app run in the same // way as continuous redraw_request_events.write(RequestRedraw); WinitSettings::desktop_app() } ApplicationWithWakeUp => { // Sending a `WakeUp` event is useful when you want the app to update the next // frame regardless of any user input. This can be used from outside Bevy, see example // `window/custom_user_event.rs` for an example usage from outside. // Note that in this example the `WakeUp` winit event will make the app run in the same // way as continuous let _ = event_loop_proxy.send_event(WakeUp); WinitSettings::desktop_app() } }; }
Update winit based on the current `ExampleMode`
update_winit
rust
bevyengine/bevy
examples/window/low_power.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/low_power.rs
Apache-2.0
pub(crate) fn cycle_modes( mut mode: ResMut<ExampleMode>, button_input: Res<ButtonInput<KeyCode>>, ) { if button_input.just_pressed(KeyCode::Space) { *mode = match *mode { ExampleMode::Game => ExampleMode::Application, ExampleMode::Application => ExampleMode::ApplicationWithRequestRedraw, ExampleMode::ApplicationWithRequestRedraw => ExampleMode::ApplicationWithWakeUp, ExampleMode::ApplicationWithWakeUp => ExampleMode::Game, }; } }
Switch between update modes when the spacebar is pressed.
cycle_modes
rust
bevyengine/bevy
examples/window/low_power.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/low_power.rs
Apache-2.0
pub(crate) fn rotate_cube( time: Res<Time>, mut cube_transform: Query<&mut Transform, With<Rotator>>, ) { for mut transform in &mut cube_transform { transform.rotate_x(time.delta_secs()); transform.rotate_local_y(time.delta_secs()); } }
Rotate the cube to make it clear when the app is updating
rotate_cube
rust
bevyengine/bevy
examples/window/low_power.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/low_power.rs
Apache-2.0
pub fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut event: EventWriter<RequestRedraw>, ) { commands.spawn(( Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Rotator, )); commands.spawn(( DirectionalLight::default(), Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y), )); event.write(RequestRedraw); commands .spawn(( Text::default(), Node { align_self: AlignSelf::FlexStart, position_type: PositionType::Absolute, top: Val::Px(12.0), left: Val::Px(12.0), ..default() }, ModeText, )) .with_children(|p| { p.spawn(TextSpan::new("Press space bar to cycle modes\n")); p.spawn((TextSpan::default(), TextColor(LIME.into()))); p.spawn((TextSpan::new("\nFrame: "), TextColor(YELLOW.into()))); p.spawn((TextSpan::new(""), TextColor(YELLOW.into()))); }); }
Set up a scene with a cube and some text
setup
rust
bevyengine/bevy
examples/window/low_power.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/low_power.rs
Apache-2.0
fn display_override( mut window: Single<&mut Window>, mut custom_text: Single<&mut Text, With<CustomText>>, ) { let text = format!( "Scale factor: {:.1} {}", window.scale_factor(), if window.resolution.scale_factor_override().is_some() { "(overridden)" } else { "(default)" } ); window.title.clone_from(&text); custom_text.0 = text; }
Set the title of the window to the current override
display_override
rust
bevyengine/bevy
examples/window/scale_factor_override.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/scale_factor_override.rs
Apache-2.0
fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) { 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 toggles scale factor overrides when enter is pressed
toggle_override
rust
bevyengine/bevy
examples/window/scale_factor_override.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/scale_factor_override.rs
Apache-2.0
fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) { 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))); } }
This system changes the scale factor override when up or down is pressed
change_scale_factor
rust
bevyengine/bevy
examples/window/scale_factor_override.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/scale_factor_override.rs
Apache-2.0
fn toggle_resolution( keys: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>, resolution: Res<ResolutionSettings>, ) { if keys.just_pressed(KeyCode::Digit1) { let res = resolution.small; window.resolution.set(res.x, res.y); } if keys.just_pressed(KeyCode::Digit2) { let res = resolution.medium; window.resolution.set(res.x, res.y); } if keys.just_pressed(KeyCode::Digit3) { let res = resolution.large; window.resolution.set(res.x, res.y); } }
This system shows how to request the window to a new resolution
toggle_resolution
rust
bevyengine/bevy
examples/window/window_resizing.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_resizing.rs
Apache-2.0
fn on_resize_system( mut text: Single<&mut Text, With<ResolutionText>>, mut resize_reader: EventReader<WindowResized>, ) { for e in resize_reader.read() { // When resolution is being changed text.0 = format!("{:.1} x {:.1}", e.width, e.height); } }
This system shows how to respond to a window being resized. Whenever the window is resized, the text will update with the new resolution.
on_resize_system
rust
bevyengine/bevy
examples/window/window_resizing.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_resizing.rs
Apache-2.0
fn toggle_vsync(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) { if input.just_pressed(KeyCode::KeyV) { window.present_mode = if matches!(window.present_mode, PresentMode::AutoVsync) { PresentMode::AutoNoVsync } else { PresentMode::AutoVsync }; info!("PRESENT_MODE: {:?}", window.present_mode); } }
This system toggles the vsync mode when pressing the button V. You'll see fps increase displayed in the console.
toggle_vsync
rust
bevyengine/bevy
examples/window/window_settings.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs
Apache-2.0
fn switch_level(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) { if input.just_pressed(KeyCode::KeyT) { window.window_level = match window.window_level { WindowLevel::AlwaysOnBottom => WindowLevel::Normal, WindowLevel::Normal => WindowLevel::AlwaysOnTop, WindowLevel::AlwaysOnTop => WindowLevel::AlwaysOnBottom, }; info!("WINDOW_LEVEL: {:?}", window.window_level); } }
This system switches the window level when pressing the T button You'll notice it won't be covered by other windows, or will be covered by all the other windows depending on the level. This feature only works on some platforms. Please check the [documentation](https://docs.rs/bevy/latest/bevy/prelude/struct.Window.html#structfield.window_level) for more details.
switch_level
rust
bevyengine/bevy
examples/window/window_settings.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs
Apache-2.0
fn toggle_window_controls(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) { let toggle_minimize = input.just_pressed(KeyCode::Digit1); let toggle_maximize = input.just_pressed(KeyCode::Digit2); let toggle_close = input.just_pressed(KeyCode::Digit3); if toggle_minimize || toggle_maximize || toggle_close { if toggle_minimize { window.enabled_buttons.minimize = !window.enabled_buttons.minimize; } if toggle_maximize { window.enabled_buttons.maximize = !window.enabled_buttons.maximize; } if toggle_close { window.enabled_buttons.close = !window.enabled_buttons.close; } } }
This system toggles the window controls when pressing buttons 1, 2 and 3 This feature only works on some platforms. Please check the [documentation](https://docs.rs/bevy/latest/bevy/prelude/struct.Window.html#structfield.enabled_buttons) for more details.
toggle_window_controls
rust
bevyengine/bevy
examples/window/window_settings.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs
Apache-2.0
fn change_title(mut window: Single<&mut Window>, time: Res<Time>) { window.title = format!( "Seconds since startup: {}", time.elapsed().as_secs_f32().round() ); }
This system will then change the title during execution
change_title
rust
bevyengine/bevy
examples/window/window_settings.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs
Apache-2.0
fn cycle_cursor_icon( mut commands: Commands, window: Single<Entity, With<Window>>, input: Res<ButtonInput<MouseButton>>, mut index: Local<usize>, cursor_icons: Res<CursorIcons>, ) { if input.just_pressed(MouseButton::Left) { *index = (*index + 1) % cursor_icons.0.len(); commands .entity(*window) .insert(cursor_icons.0[*index].clone()); } else if input.just_pressed(MouseButton::Right) { *index = if *index == 0 { cursor_icons.0.len() - 1 } else { *index - 1 }; commands .entity(*window) .insert(cursor_icons.0[*index].clone()); } }
This system cycles the cursor's icon through a small set of icons when clicking
cycle_cursor_icon
rust
bevyengine/bevy
examples/window/window_settings.rs
https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs
Apache-2.0
fn game_plugin(app: &mut App) { app.add_systems(Startup, (spawn_player, window_title_system).chain()); app.add_systems(Update, spell_casting); }
Splitting a Bevy project into multiple smaller plugins can make it more testable. We can write tests for individual plugins in isolation, as well as for the entire project.
game_plugin
rust
bevyengine/bevy
tests/how_to_test_apps.rs
https://github.com/bevyengine/bevy/blob/master/tests/how_to_test_apps.rs
Apache-2.0
fn count_ambiguities(sub_app: &SubApp) -> AmbiguitiesCount { let schedules = sub_app.world().resource::<Schedules>(); let mut ambiguities = <HashMap<_, _>>::default(); for (_, schedule) in schedules.iter() { let ambiguities_in_schedule = schedule.graph().conflicting_systems().len(); ambiguities.insert(schedule.label(), ambiguities_in_schedule); } AmbiguitiesCount(ambiguities) }
Returns the number of conflicting systems per schedule.
count_ambiguities
rust
bevyengine/bevy
tests/ecs/ambiguity_detection.rs
https://github.com/bevyengine/bevy/blob/master/tests/ecs/ambiguity_detection.rs
Apache-2.0
fn setup_3d( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { // plane commands.spawn(( Mesh3d(meshes.add(Plane3d::default().mesh().size(5.0, 5.0))), MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))), )); // cube commands.spawn(( Mesh3d(meshes.add(Cuboid::default())), MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))), Transform::from_xyz(0.0, 0.5, 0.0), )); // light commands.spawn(( PointLight { shadows_enabled: true, ..default() }, Transform::from_xyz(4.0, 8.0, 4.0), )); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), )); }
A simple 3d scene, taken from the `3d_scene` example
setup_3d
rust
bevyengine/bevy
tests/window/minimizing.rs
https://github.com/bevyengine/bevy/blob/master/tests/window/minimizing.rs
Apache-2.0
fn setup_2d(mut commands: Commands) { commands.spawn(( Camera2d, Camera { // render the 2d camera after the 3d camera order: 1, // do not use a clear color clear_color: ClearColorConfig::None, ..default() }, )); commands.spawn(Sprite::from_color( Color::srgb(0.25, 0.25, 0.75), Vec2::new(50.0, 50.0), )); }
A simple 2d scene, taken from the `rect` example
setup_2d
rust
bevyengine/bevy
tests/window/minimizing.rs
https://github.com/bevyengine/bevy/blob/master/tests/window/minimizing.rs
Apache-2.0