From 53157c0801e064a643eff39cc470475b83f95464 Mon Sep 17 00:00:00 2001 From: Ida Iyes Date: Sun, 18 Sep 2022 22:49:27 +0000 Subject: [PATCH] Sprite: allow using a sub-region (Rect) of the image (#6014) Very small change that improves the usability of `Sprite`. Before this PR, the only way to render a portion of an `Image` was to create a `TextureAtlas` and use `TextureAtlasSprite`/`SpriteSheetBundle`. This can be very annoying for one-off use cases, like if you just want to remove a border from an image, or something. Using `Sprite`/`SpriteBundle` always meant that the entire full image would be rendered. This PR adds an optional `rect` field to `Sprite`, allowing a sub-rectangle of the image to be rendered. This is similar to how texture atlases work, but does not require creating a texture atlas asset, making it much more convenient and efficient for quick one-off use cases. Given how trivial this change is, it really felt like missing functionality in Bevy's sprites API. ;) ## Changelog Added: - `rect` field on `Sprite`: allows rendering a portion of the sprite's image; more convenient for one-off use cases, than creating a texture atlas. --- crates/bevy_sprite/src/render/mod.rs | 3 +-- crates/bevy_sprite/src/sprite.rs | 5 ++++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index 70ccd029e2d9a..95d3b9e3f6662 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -257,8 +257,7 @@ pub fn extract_sprites( entity, color: sprite.color, transform: *transform, - // Use the full texture - rect: None, + rect: sprite.rect, // Pass the custom size custom_size: sprite.custom_size, flip_x: sprite.flip_x, diff --git a/crates/bevy_sprite/src/sprite.rs b/crates/bevy_sprite/src/sprite.rs index 56dc1b86c935d..da2a6de1c2cf1 100644 --- a/crates/bevy_sprite/src/sprite.rs +++ b/crates/bevy_sprite/src/sprite.rs @@ -1,5 +1,5 @@ use bevy_ecs::component::Component; -use bevy_math::Vec2; +use bevy_math::{Rect, Vec2}; use bevy_reflect::Reflect; use bevy_render::color::Color; @@ -15,6 +15,9 @@ pub struct Sprite { /// An optional custom size for the sprite that will be used when rendering, instead of the size /// of the sprite's image pub custom_size: Option, + /// An optional rectangle representing the region of the sprite's image to render, instead of + /// rendering the full image. This is an easy one-off alternative to using a texture atlas. + pub rect: Option, /// [`Anchor`] point of the sprite in the world pub anchor: Anchor, }