How can you change a SpriteComponent color?
Asked Answered
D

1

6

I have a query system that finds an object in which the mouse is over. This is not a button, but, I wish to change the color. I'm not sure where to start. What property would I query and how would I change it? Currently, I have the following:

fn mouse_move(mut commands: Commands, cursor: Res<Cursor>, mut query: Query<(&Translation,&mut Sprite,&Box,&Name)>) 
{
    for (translation,mut sprite,_box,name) in &mut query.iter() {
        let cursor_tup = translate_cursor ((cursor.0,cursor.1));
        let cursor_vec = Vec3::new(cursor_tup.0,cursor_tup.1,0.0);
        if collides(cursor_vec,Vec2::new(1.0,1.0),translation.0,sprite.size) {
            println!("{}",name.0);
        }
    }
}
Derinna answered 24/8, 2020 at 5:43 Comment(0)
C
8
fn mouse_move(mut commands: Commands, cursor: Res<Cursor>, mut materials: ResMut<Assets<ColorMaterial>>, mut query: Query<(&Translation,&mut Sprite,&Box,&Name, &mut Handle<ColorMaterial>)>) 
{
    for (translation,mut sprite,_box,name, color) in &mut query.iter() {
        let cursor_tup = translate_cursor ((cursor.0,cursor.1));
        let cursor_vec = Vec3::new(cursor_tup.0,cursor_tup.1,0.0);
        if collides(cursor_vec,Vec2::new(1.0,1.0),translation.0,sprite.size) {
            println!("{}",name.0);
            let mut color_mat = materials.get_mut(&color).unwrap();
            color_mat.color = Color::rgb(1.0,1.0,1.0);
        }
    }
}

So you have to take the material handle associated with entity, and then have to get the ColorMaterial from Assets.

Currently the color should just change to white.

Coumarone answered 24/8, 2020 at 11:4 Comment(2)
Awesome, I didn't realize I needed Handle<>Derinna
Good answer, but alas, not quite what I was looking for. Note that the OP called it SpriteComponent, but it's really a Material Component, and only works for things that have a Material assigned - which doesn't include (far as I can tell), Sprites or SpriteBundles, etc.Lovel

© 2022 - 2024 — McMap. All rights reserved.