How to assign sprites to custom game objects without messing up lifetimes? #1077
-
Hi, since the introductions used meta sprites and the concept seemed useful, I thought it would be a good idea to create my own custom pub struct MetaSprite<'a> {
pos: Vector2D<Fixed>,
hflip: bool,
vflip: bool,
priority: Priority,
sprites: Vec<(&'a Sprite, Vector2D<i32>, (bool, bool))>,
total_size: Vector2D<i32>,
} The only problem now shows up when I try to show the pub fn show(&self, frame: &mut GraphicsFrame) {
for (sprite, offset, flip_bools) in &self.sprites {
let sprite_size = sprite.size().to_width_height();
let mut flip_offset: Vector2D<i32> = vec2(0, 0);
if self.hflip { flip_offset.x = self.total_size.x - sprite_size.0 as i32 };
if self.vflip { flip_offset.y = self.total_size.y - sprite_size.1 as i32 };
Object::new(*sprite) // <- error occurs here
.set_pos(self.pos.round() + *offset - flip_offset)
.set_hflip(flip_bools.0 != self.hflip)
.set_vflip(flip_bools.1 != self.vflip)
.set_priority(self.priority)
.show(frame);
}
} Here, I always get the following error: I can somewhat follow the error, but I can't come up with a solution. If I don't dereference the sprite, then the argument throws an error on the My understanding of lifetimes is admittedly not good, so maybe I'm missing something obvious. Should I go about this a whole different way? Did I just miss some detail of where else to annotate another lifetime or something like that? Any help or advice how to approach this differently would be appreciated. EDIT: Just as an example of how the meta sprite is ultimately created: let mut sel_marker = MetaSprite::new(
vec!(
(sprites::MARKER.sprite(0), vec2(0, 0), (false, false)),
(sprites::MARKER.sprite(0), vec2(32, 0), (false, false)),
(sprites::MARKER.sprite(0), vec2(64, 0), (false, false)),
),
vec2(96, 8)
); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
We reference count sprites, so cloning is cheap and doesn't use more vram. |
Beta Was this translation helpful? Give feedback.
My apologies, I thought you had
SpriteVram
s for some reason.You should be able to use
'static
references to sprites. Thesprite
method you're using gives aSprite
with the static lifetime: https://docs.rs/agb/latest/agb/display/object/struct.Tag.html#method.spriteYou don't want to make copies of the
Sprite
data itself, which is why we don't let it happen.Object::new
acceptsInto<SpriteVram>
, which includesSpriteVram
, but that's an aside.