Last active
February 24, 2023 19:30
-
-
Save rparrett/548d2d94b1a8908fbf0b58ed1f01a139 to your computer and use it in GitHub Desktop.
Bevy 0.9 + bevy_egui: changing a cube's color with sliders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mashup of | |
// https://github.com/mvlabat/bevy_egui/blob/v0.19.0/examples/simple.rs | |
// https://github.com/bevyengine/bevy/blob/v0.9.1/examples/3d/3d_scene.rs | |
// In cargo.toml: | |
// [dependencies] | |
// bevy = "0.9" | |
// bevy_egui = "0.19" | |
use bevy::prelude::*; | |
use bevy_egui::{egui, EguiContext, EguiPlugin}; | |
#[derive(Resource, Default)] | |
struct CubeSettings { | |
r: f32, | |
g: f32, | |
b: f32, | |
} | |
fn main() { | |
App::new() | |
.add_plugins(DefaultPlugins) | |
.add_plugin(EguiPlugin) | |
.add_system(ui) | |
.add_system(update_cube) | |
.add_startup_system(setup) | |
.init_resource::<CubeSettings>() | |
.run(); | |
} | |
fn setup( | |
mut commands: Commands, | |
mut meshes: ResMut<Assets<Mesh>>, | |
mut materials: ResMut<Assets<StandardMaterial>>, | |
settings: Res<CubeSettings>, | |
) { | |
// cube | |
commands.spawn(PbrBundle { | |
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), | |
material: materials.add(Color::rgb(settings.r, settings.g, settings.b).into()), | |
transform: Transform::from_xyz(0.0, 0.5, 0.0), | |
..default() | |
}); | |
// light | |
commands.spawn(PointLightBundle { | |
point_light: PointLight { | |
intensity: 1500.0, | |
shadows_enabled: true, | |
..default() | |
}, | |
transform: Transform::from_xyz(4.0, 8.0, 4.0), | |
..default() | |
}); | |
// camera | |
commands.spawn(Camera3dBundle { | |
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), | |
..default() | |
}); | |
} | |
fn ui(mut egui_context: ResMut<EguiContext>, mut settings: ResMut<CubeSettings>) { | |
egui::Window::new("Color").show(egui_context.ctx_mut(), |ui| { | |
ui.add(egui::Slider::new(&mut settings.r, 0.0..=1.0).text("red")); | |
ui.add(egui::Slider::new(&mut settings.g, 0.0..=1.0).text("green")); | |
ui.add(egui::Slider::new(&mut settings.b, 0.0..=1.0).text("blue")); | |
}); | |
} | |
fn update_cube( | |
settings: Res<CubeSettings>, | |
query: Query<&Handle<StandardMaterial>>, | |
mut materials: ResMut<Assets<StandardMaterial>>, | |
) { | |
if !settings.is_changed() { | |
return; | |
} | |
let handle = query.single(); | |
if let Some(mut material) = materials.get_mut(handle) { | |
material.base_color = Color::rgb(settings.r, settings.g, settings.b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment