Skip to content

Instantly share code, notes, and snippets.

@thebluefish
Created November 11, 2024 17:17
Show Gist options
  • Save thebluefish/061ba145fa9fd78cc0badbe6e9113fae to your computer and use it in GitHub Desktop.
Save thebluefish/061ba145fa9fd78cc0badbe6e9113fae to your computer and use it in GitHub Desktop.
use std::time::Duration;
use bevy::color::palettes::css::RED;
use bevy::math::VectorSpace;
use bevy::prelude::*;
use bevy::time::common_conditions::once_after_delay;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, |mut commands: Commands| {
commands.spawn(Camera2dBundle::default());
})
.add_systems(Update, start_interpolation.run_if(once_after_delay(Duration::from_secs(2))))
.add_systems(Update, interpolate.run_if(resource_exists::<TargetClearColor>))
.run();
}
#[derive(Resource)]
pub struct TargetClearColor {
start: Duration,
duration: Duration,
// LinearRgba is generally good, but you can achieve different effects with others like HSL
start_color: LinearRgba,
end_color: LinearRgba,
}
fn start_interpolation(mut commands: Commands, time: Res<Time>, clear: Res<ClearColor>) {
commands.insert_resource(TargetClearColor {
start: time.elapsed(),
duration: Duration::from_secs(2),
start_color: LinearRgba::from(*clear.clone()),
end_color: RED.into(),
});
}
fn interpolate(mut commands: Commands, time: Res<Time>, target: ResMut<TargetClearColor>, mut clear: ResMut<ClearColor>) {
// lerp factor starts at 0 & ends at 1
let elapsed: Duration = time.elapsed() - target.start;
let mut ratio = elapsed.div_duration_f32(target.duration);
if ratio >= 1. {
ratio = 1.;
commands.remove_resource::<TargetClearColor>();
}
let color_lerp = target.start_color.lerp(target.end_color, ratio);
clear.0 = Color::from(color_lerp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment