Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

in Rust macroquad engine, how to make sure one moving direction is selected

im coding a snake game in rust to learn the macroquad engine, im still a rust beginner and really interested in the language

the problem is i dont seem to be able to make the snake go in a single direction, like if the head is going up, dont go down at the same time

here is the update method used on the head of the snake

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 pub fn update(&mut self, dt: f32) {
    let v_mv = match (is_key_down(KeyCode::Down), is_key_down(KeyCode::Up)) {
        (true, false) => 1f32,
        (false, true) => -1f32,
        _ => 0f32,
    };
    let h_mv = match (is_key_down(KeyCode::Right), is_key_down(KeyCode::Left)) {
        (true, false) => 1f32,
        (false, true) => -1f32,
        _ => 0f32,
    };
    self.player.x += dt * PLAYER_SPEED * h_mv;
    self.player.y += dt * PLAYER_SPEED * v_mv;
}

there is nothing preventing the snake from moving in x and y at the same time.

>Solution :

I would merge the two matches:

pub fn update(&mut self, dt: f32) {
    let (v_mv, h_mv): (f32, f32) = match (
        is_key_down(KeyCode::Down),
        is_key_down(KeyCode::Up),
        is_key_down(KeyCode::Right),
        is_key_down(KeyCode::Left),
    ) {
        (true, false, false, false) => (1.0, 0.0),
        (false, true, false, false) => (-1.0, 0.0),
        (false, false, true, false) => (0.0, 1.0),
        (false, false, false, true) => (0.0, -1.0),
        _ => (0.0, 0.0),
    };

    self.player.x += dt * PLAYER_SPEED * h_mv;
    self.player.y += dt * PLAYER_SPEED * v_mv;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading