fix flickering and add movement

This commit is contained in:
Yash Karandikar 2022-03-07 12:58:02 -06:00
parent 056f470a82
commit 7d41502e9e
Signed by untrusted user: karx
GPG key ID: A794DA2529474BA5
2 changed files with 31 additions and 5 deletions

View file

@ -71,7 +71,7 @@ impl Iterator for Events {
pub struct Sprite {
rect: Rect,
surf: Surface<'static>
surf: Surface<'static>,
}
impl Sprite {
@ -84,11 +84,14 @@ impl Sprite {
Ok(Self {
rect: dest_rect,
surf
surf,
})
}
pub fn draw(&self, canvas: &mut Canvas<Window>, events: &Events) -> Result<()> {
canvas.fill_rect(None)?;
canvas.clear();
let mut surface = canvas.window().surface(events.as_ref())?;
self.surf.blit(None, &mut *surface, self.rect)?;
@ -97,6 +100,14 @@ impl Sprite {
Ok(())
}
pub fn translate(&mut self, position: (i32, i32)) {
let new_x = self.rect.x() - position.0;
let new_y = self.rect.y() - position.1;
self.rect.set_x(new_x);
self.rect.set_y(new_y);
}
}
pub struct Game {
@ -127,18 +138,21 @@ impl Game {
let mut canvas = window.into_canvas().build()?;
let mut event_pump = sdl_context.event_pump()?;
let event_pump = sdl_context.event_pump()?;
let mut events = Events {
pump: event_pump
};
loop {
if self.stopped.get() {
break;
}
canvas.set_draw_color(Color::RGB(0, 0, 0));
canvas.clear();
func(&mut canvas, &mut events);
canvas.present();
// canvas.present();
}
Ok(())

View file

@ -4,7 +4,7 @@ fn main() {
let game = Game::new("catbox demo", 1000, 800);
let mut i = 0;
let s = Sprite::new("/home/yashkarandikar/code/catbox/duck.png", 500, 400).unwrap();
let mut s = Sprite::new("/home/yashkarandikar/code/catbox/duck.png", 500, 400).unwrap();
game.run(|canvas, event_pump| {
i = (i + 1) % 255;
// canvas.set_draw_color(catbox::Color::RGB(i, 64, 255));
@ -22,6 +22,18 @@ fn main() {
keycode: Some(Keycode::Escape),
..
} => game.terminate(),
Event::KeyDown { keycode, .. } => {
let offset = match keycode.unwrap() {
Keycode::W | Keycode::Up => (0, 5),
Keycode::S | Keycode::Down => (0, -5),
Keycode::A | Keycode::Left => (-5, 0),
Keycode::D | Keycode::Right => (5, 0),
_ => (0, 0)
};
s.translate(offset);
}
_ => {}
}
}