Created
January 24, 2023 16:51
-
-
Save rparrett/91507e719af3a1750011df3138af16d8 to your computer and use it in GitHub Desktop.
Bevy 0.9 - Changing a 2d material
This file contains 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
use bevy::{prelude::*, sprite::MaterialMesh2dBundle}; | |
#[derive(Resource)] | |
struct AlphaMaterialHandle(Handle<ColorMaterial>); | |
impl FromWorld for AlphaMaterialHandle { | |
fn from_world(world: &mut World) -> Self { | |
let mut materials = world.resource_mut::<Assets<ColorMaterial>>(); | |
Self(materials.add(ColorMaterial::from(Color::PURPLE))) | |
} | |
} | |
fn main() { | |
App::new() | |
.add_plugins(DefaultPlugins) | |
.init_resource::<AlphaMaterialHandle>() | |
.add_startup_system(setup) | |
.add_system(change_alpha) | |
.run(); | |
} | |
fn setup( | |
mut commands: Commands, | |
mut meshes: ResMut<Assets<Mesh>>, | |
alpha_material: Res<AlphaMaterialHandle>, | |
) { | |
commands.spawn(Camera2dBundle::default()); | |
// Circle | |
commands.spawn(MaterialMesh2dBundle { | |
mesh: meshes.add(shape::Circle::new(50.).into()).into(), | |
material: alpha_material.0.clone(), | |
transform: Transform::from_translation(Vec3::new(-10., 0., 1.)), | |
..default() | |
}); | |
// Hexagon | |
commands.spawn(MaterialMesh2dBundle { | |
mesh: meshes.add(shape::RegularPolygon::new(50., 6).into()).into(), | |
material: alpha_material.0.clone(), | |
transform: Transform::from_translation(Vec3::new(10., 0., 0.)), | |
..default() | |
}); | |
} | |
fn change_alpha( | |
alpha_material: Res<AlphaMaterialHandle>, | |
mut materials: ResMut<Assets<ColorMaterial>>, | |
time: Res<Time>, | |
) { | |
let alpha = (1. + time.elapsed_seconds().sin()) / 2.; | |
if let Some(mat) = materials.get_mut(&alpha_material.0) { | |
mat.color.set_a(alpha); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment