Create SpriteCollection struct

This commit is contained in:
Yash Karandikar 2022-03-29 11:36:51 -05:00
parent 51f16b8fec
commit 8afa9e2485
2 changed files with 67 additions and 4 deletions

View file

@ -49,7 +49,7 @@
//! }
//! ```
use std::{cell::Cell, path::Path};
use std::{cell::Cell, path::Path, ops::{DerefMut, Deref}};
use sdl2::{
image::ImageRWops,
@ -241,6 +241,46 @@ impl Sprite {
}
}
pub struct SpriteCollection {
v: Vec<Sprite>,
}
impl SpriteCollection {
pub fn new() -> Self {
Self {
v: Vec::new()
}
}
pub fn with_capacity(cap: usize) -> Self {
Self {
v: Vec::with_capacity(cap)
}
}
pub fn draw(&mut self, ctx: &mut Context) -> Result<()> {
for s in self.v.iter_mut() {
s.draw(ctx)?;
}
Ok(())
}
}
impl Deref for SpriteCollection {
type Target = Vec<Sprite>;
fn deref(&self) -> &Self::Target {
&self.v
}
}
impl DerefMut for SpriteCollection {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.v
}
}
/// Game context.
///
/// In most cases, this should never actually be used; instead, just pass it around to the various cat-box functions such as [`Sprite::draw()`].

View file

@ -1,13 +1,21 @@
use cat_box::{draw_text, Event, Game, Keycode, Sprite};
use cat_box::{draw_text, Event, Game, Keycode, Sprite, SpriteCollection};
fn main() {
let game = Game::new("catbox demo", 1000, 800);
let mut i = 0.0;
let mut i = 0u8;
let mut s = Sprite::new("duck.png", 500, 400).unwrap();
let mut s2 = Sprite::new("duck.png", 400, 500).unwrap();
let mut coll = SpriteCollection::new();
for n in 0..10 {
for o in 0..8 {
let x = Sprite::new("duck.png", n * 100, o * 100).unwrap();
coll.push(x);
}
}
game.run(|ctx, event_pump| {
i = (i + 1.0) % 360.0;
i = (i + 1) % 255;
ctx.set_background_colour(i as u8, 64, 255);
draw_text(
@ -31,6 +39,16 @@ fn main() {
let angle = (y_diff as f64).atan2(x_diff as f64);
s.set_angle(angle.to_degrees());
for spr in coll.iter_mut() {
let (start_x, start_y) = spr.position();
let m = sdl2::mouse::MouseState::new(event_pump.as_ref());
let x_diff = m.x() - start_x;
let y_diff = m.y() - start_y;
let angle = (y_diff as f64).atan2(x_diff as f64);
spr.set_angle(angle.to_degrees());
}
for event in event_pump {
match event {
Event::Quit { .. }
@ -49,6 +67,10 @@ fn main() {
};
s.translate(offset);
for spr in coll.iter_mut() {
spr.translate(offset);
}
}
_ => {}
}
@ -56,6 +78,7 @@ fn main() {
s2.draw(ctx).unwrap();
s.draw(ctx).unwrap();
coll.draw(ctx).unwrap();
})
.unwrap();
}