CpILL
CpILL

Reputation: 6979

How to get the actual pixel size of a transformed sprite in Bevy?

This seems like it should be easy but I haven't found a straight answer on how to do this anywhere.
So, in Bevy, I'm trying to have sprites spawn, move around and detect clicks on them and then do something. So in order to figure out if a sprite I clicked/touched I need to know its bounding box?

So I spawn new SpriteBundles and apply a transform to them to scale them down (might scale them dynamically in the future)

commands. Spawn((
    SpriteBundle {
            transform: Transform::from_xyz(x, y, 0.0).with_scale(Vec3::splat(0.1)),
            texture: asset_server.load("images/S.png"),
            ..default()
        },
    ...
));
...

I found this example of reading an images dimensions

fn confine(
    mut confinable_query: Query<(&mut Transform, &Handle<Image>), With<Confinable>>,
    assets: Res<Assets<Image>>
) {
    let window = window_query.get_single().unwrap();
 
    for (mut transform, image_handle) in confinable_query.iter_mut() {
        let image_dimensions = assets.get(image_handle).unwrap().size();
...

but it seems the image_dimensions are the original image (they don't change with or without scale transform applied) not the new scaled size? How do i get the bounding box of a scaled sprite in real time?

Upvotes: 0

Views: 1075

Answers (1)

CpILL
CpILL

Reputation: 6979

from but the gist is you can pull the scaling factor from the transform.

fn print_sprite_bounding_boxes(
    mut sprite_query: Query<(&Transform, &Handle<Image>), With<Sprite>>,
    assets: Res<Assets<Image>>,
) {
    for (transform, image_handle) in sprite_query.iter_mut() {
        let image_dimensions = assets.get(image_handle).unwrap().size();
        let scaled_image_dimension = image_dimensions * transform.scale.truncate();
        let bounding_box = Rect::from_center_size(transform.translation.truncate(), scaled_image_dimension);

        println!("bounding_box: {:?}", bounding_box);
    }
}

Upvotes: 0

Related Questions