diff --git a/crates/bevy_sprite/src/lib.rs b/crates/bevy_sprite/src/lib.rs index 08f6484cc39da..a8189c6d4d8cd 100644 --- a/crates/bevy_sprite/src/lib.rs +++ b/crates/bevy_sprite/src/lib.rs @@ -194,14 +194,18 @@ pub fn calculate_bounds_2d( } } for (entity, sprite, texture_handle, atlas) in &sprites_to_recalculate_aabb { - if let Some(size) = sprite.custom_size.or_else(|| match atlas { - // We default to the texture size for regular sprites - None => images.get(texture_handle).map(|image| image.size_f32()), - // We default to the drawn rect for atlas sprites - Some(atlas) => atlas - .texture_rect(&atlases) - .map(|rect| rect.size().as_vec2()), - }) { + if let Some(size) = sprite + .custom_size + .or_else(|| sprite.rect.map(|rect| rect.size())) + .or_else(|| match atlas { + // We default to the texture size for regular sprites + None => images.get(texture_handle).map(|image| image.size_f32()), + // We default to the drawn rect for atlas sprites + Some(atlas) => atlas + .texture_rect(&atlases) + .map(|rect| rect.size().as_vec2()), + }) + { let aabb = Aabb { center: (-sprite.anchor.as_vec() * size).extend(0.0).into(), half_extents: (0.5 * size).extend(0.0).into(), @@ -226,7 +230,7 @@ impl ExtractComponent for SpriteSource { #[cfg(test)] mod test { - use bevy_math::Vec2; + use bevy_math::{Rect, Vec2, Vec3A}; use bevy_utils::default; use super::*; @@ -336,4 +340,52 @@ mod test { // Check that the AABBs are not equal assert_ne!(first_aabb, second_aabb); } + + #[test] + fn calculate_bounds_2d_correct_aabb_for_sprite_with_custom_rect() { + // Setup app + let mut app = App::new(); + + // Add resources and get handle to image + let mut image_assets = Assets::::default(); + let image_handle = image_assets.add(Image::default()); + app.insert_resource(image_assets); + let mesh_assets = Assets::::default(); + app.insert_resource(mesh_assets); + let texture_atlas_assets = Assets::::default(); + app.insert_resource(texture_atlas_assets); + + // Add system + app.add_systems(Update, calculate_bounds_2d); + + // Add entities + let entity = app + .world_mut() + .spawn(( + Sprite { + rect: Some(Rect::new(0., 0., 0.5, 1.)), + anchor: Anchor::TopRight, + ..default() + }, + image_handle, + )) + .id(); + + // Create AABB + app.update(); + + // Get the AABB + let aabb = *app + .world_mut() + .get_entity(entity) + .expect("Could not find entity") + .get::() + .expect("Could not find AABB"); + + // Verify that the AABB is at the expected position + assert_eq!(aabb.center, Vec3A::new(-0.25, -0.5, 0.)); + + // Verify that the AABB has the expected size + assert_eq!(aabb.half_extents, Vec3A::new(0.25, 0.5, 0.)); + } }