keys or something idk

This commit is contained in:
SimonFJ20 2024-04-08 15:03:50 +02:00
parent 3beca27b67
commit 7e2bac57cd
2 changed files with 25 additions and 10 deletions

View File

@ -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<Entity>,
systems: &'context mut Vec<Rc<dyn System>>,
textures: &'context mut Vec<(Id, Texture<'game>)>,
currently_pressed_keys: &'context HashSet<Keycode>,
}
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<dyn Component>)>,
systems: Vec<Rc<dyn System>>,
textures: Vec<(Id, Texture<'a>)>,
currently_pressed_keys: HashSet<Keycode>,
}
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());
}
_ => {}
}
}

View File

@ -10,7 +10,7 @@ use engine::Component;
#[derive(Component)]
struct Player {
sprite: Option<Sprite>,
sprite: Sprite,
}
#[derive(Component)]
@ -36,13 +36,18 @@ impl System for PlayerRenderer {
let &mut Position(x, y) = ctx.entity_component::<Position>(id);
let player = ctx.entity_component::<Player>(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();
}