From 7e2bac57cd53336c1576e8c4cf389311bb106c12 Mon Sep 17 00:00:00 2001 From: SimonFJ20 Date: Mon, 8 Apr 2024 15:03:50 +0200 Subject: [PATCH] keys or something idk --- src/engine.rs | 17 ++++++++++++++++- src/main.rs | 18 +++++++++--------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index bf360ac..ba03a1b 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1,11 +1,13 @@ use std::any::{Any, TypeId}; +use std::collections::HashSet; use std::rc::Rc; use std::time::Duration; +pub use sdl2::keyboard::Keycode; + use sdl2::{ event::Event, image::{self, LoadTexture, Sdl2ImageContext}, - keyboard::Keycode, pixels::Color, rect::Rect, render::{Canvas, Texture, TextureCreator}, @@ -64,6 +66,7 @@ where entities: &'context mut Vec, systems: &'context mut Vec>, textures: &'context mut Vec<(Id, Texture<'game>)>, + currently_pressed_keys: &'context HashSet, } impl<'context, 'game> Context<'context, 'game> { @@ -148,6 +151,10 @@ impl<'context, 'game> Context<'context, 'game> { system.on_add(self); self.systems.push(system) } + + pub fn key_pressed(&self, keycode: Keycode) -> bool { + self.currently_pressed_keys.contains(&keycode) + } } pub trait System { @@ -169,6 +176,7 @@ pub struct Game<'a> { components: Vec<(u64, Box)>, systems: Vec>, textures: Vec<(Id, Texture<'a>)>, + currently_pressed_keys: HashSet, } impl<'game> Game<'game> { @@ -200,6 +208,7 @@ impl<'game> Game<'game> { components: vec![], systems: vec![], textures: vec![], + currently_pressed_keys: HashSet::new(), }) } @@ -212,6 +221,12 @@ impl<'game> Game<'game> { keycode: Some(Keycode::Escape), .. } => break 'running, + Event::KeyDown { keycode, .. } => { + self.currently_pressed_keys.insert(keycode.unwrap()); + } + Event::KeyUp { keycode, .. } => { + self.currently_pressed_keys.remove(&keycode.unwrap()); + } _ => {} } } diff --git a/src/main.rs b/src/main.rs index 5251ee4..fa1a7e7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use engine::Component; #[derive(Component)] struct Player { - sprite: Option, + sprite: Sprite, } #[derive(Component)] @@ -36,13 +36,18 @@ impl System for PlayerRenderer { let &mut Position(x, y) = ctx.entity_component::(id); let player = ctx.entity_component::(id); - let sprite = player.sprite.unwrap(); - ctx.draw_sprite(&sprite, x, y)?; + ctx.draw_sprite(&player.sprite, x, y)?; } Ok(()) } } +struct PlayerMovement; + +impl System for PlayerMovement { + fn on_update(&self, _ctx: &mut engine::Context) -> Result<(), engine::Error> {} +} + fn main() { let mut game = engine::Game::new().unwrap(); @@ -50,11 +55,6 @@ fn main() { context.add_system(Rc::new(PlayerRenderer)); context.add_system(Rc::new(Gravity)); let sprite = context.load_sprite("textures/player.png").unwrap(); - context.spawn(vec![ - Box::new(Player { - sprite: Some(sprite), - }), - Box::new(Position(16, 0)), - ]); + context.spawn(vec![Box::new(Player { sprite }), Box::new(Position(16, 0))]); game.run(); }