Skip to content

Instantly share code, notes, and snippets.

@IceSentry
Created June 26, 2024 03:28
Show Gist options
  • Save IceSentry/3552f31b4c4d00f99c03aab0ccdd753a to your computer and use it in GitHub Desktop.
Save IceSentry/3552f31b4c4d00f99c03aab0ccdd753a to your computer and use it in GitHub Desktop.
bevy UiMaterial image slider
//! Demonstrates the use of [`UiMaterials`](UiMaterial) and how to change material values
use bevy::color::palettes::css::BLACK;
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy::render::render_resource::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(UiMaterialPlugin::<CustomUiMaterial>::default())
.add_systems(Startup, setup)
.add_systems(Update, animate)
.run();
}
fn setup(
mut commands: Commands,
mut ui_materials: ResMut<Assets<CustomUiMaterial>>,
asset_server: Res<AssetServer>,
) {
// Camera so we can see UI
commands.spawn(Camera2dBundle::default());
commands
.spawn(NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
})
.with_children(|parent| {
parent.spawn(MaterialNodeBundle {
style: Style {
position_type: PositionType::Absolute,
width: Val::Px(350.0),
height: Val::Px(150.0),
..default()
},
material: ui_materials.add(CustomUiMaterial {
slider: 0.5,
color_texture: asset_server.load("branding/banner.png"),
}),
..default()
});
});
}
#[derive(AsBindGroup, Asset, TypePath, Debug, Clone)]
struct CustomUiMaterial {
#[uniform(0)]
slider: f32,
#[texture(1)]
#[sampler(2)]
color_texture: Handle<Image>,
}
impl UiMaterial for CustomUiMaterial {
fn fragment_shader() -> ShaderRef {
"slider.wgsl".into()
}
}
fn animate(
mut materials: ResMut<Assets<CustomUiMaterial>>,
q: Query<&Handle<CustomUiMaterial>>,
time: Res<Time>,
) {
let duration = 2.0;
for handle in &q {
if let Some(material) = materials.get_mut(handle) {
material.slider = (time.elapsed_seconds() % duration) / duration;
}
}
}
// This shader draws a circle with a given input color
#import bevy_ui::ui_vertex_output::UiVertexOutput
@group(1) @binding(0) var<uniform> slider: f32;
@group(1) @binding(1) var material_color_texture: texture_2d<f32>;
@group(1) @binding(2) var material_color_sampler: sampler;
@fragment
fn fragment(in: UiVertexOutput) -> @location(0) vec4<f32> {
if in.uv.x < slider {
return textureSample(material_color_texture, material_color_sampler, in.uv);
} else {
return vec4(0.0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment