Is changing color of a sprite possible? #2869
-
Hi, Is there a way to change the tint or color of a sprite using a system, for example to fade in or out an image? Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Yes. Bevy 0.6+Bevy Migration Guide 0.5 to 0.6: SpriteBundle and Sprite use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.add_system(change_colors)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn_bundle(Camera2dBundle::default());
commands.spawn_bundle(SpriteBundle {
texture: asset_server.load("branding/icon.png"),
..default()
});
}
fn change_colors(mut query: Query<&mut Sprite>) {
for mut sprite in query.iter_mut() {
// your color changing logic here instead:
let a = sprite.color.a();
sprite.color.set_a(a * 0.99);
}
} Bevy 0.5-
Below is the sprite example with one system added, which changes the alpha to 99% (multiplicatively) each frame. use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.add_system(change_colors)
.run();
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
let texture_handle = asset_server.load("branding/icon.png");
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
commands.spawn_bundle(SpriteBundle {
material: materials.add(texture_handle.into()),
..Default::default()
});
}
fn change_colors(
query: Query<&Handle<ColorMaterial>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
for handle in query.iter() {
let color = &mut materials.get_mut(handle).unwrap().color;
// your color changing logic here instead:
color.set_a(color.a() * 0.99);
}
} |
Beta Was this translation helpful? Give feedback.
-
Update for bevy 0.6+ Spawn your SpriteBundle as usual commands
.spawn_bundle(SpriteBundle {
texture: assets.myimage.clone(), // This will be different for you
..default()
})
.insert(MyComponent); Then query for the Sprite Component of the Bundle fn change_colors(mut query: Query<(&mut Sprite), (With<MyComponent>)>) {
for mut sprite in query.iter_mut() {
sprite.color = Color::rgb(1.0, 0.0, 0.0);
}
} Notice the optional MyComponent to identify the objects to color. |
Beta Was this translation helpful? Give feedback.
Yes.
Bevy 0.6+
Bevy Migration Guide 0.5 to 0.6: SpriteBundle and Sprite