Fly away
A game is not much fun without something happening on the screen. To begin with, we will show a circle that we can steer with the arrow keys on the keyboard.
Implementation
The first two lines of the main
function uses the functions screen_width()
and screen_height()
to get the width and height of the application window.
These values are divided by 2
to get the coordinates of the center of the
window, and stored in the variables x
and y
. These variables will be used
to decide where to draw the circle on the screen.
let mut x = screen_width() / 2.0;
let mut y = screen_height() / 2.0;
Handle keyboard input
Inside the main loop we will still clear the background as it should be done
in each frame. After that there are four if
statements that check if any of
the arrow keys on the keyboard has been pressed. The variables x
and y
are
changed to move the circle in the corresponding direction.
The function is_key_down()
returns true if the given key is being
pressed during the current frame. The argument is of the enum KeyCode
that
contains all keys available on the keyboard.
You can read more about how the Rust enum
feature
works in the Rust book.
if is_key_down(KeyCode::Right) {
x += 1.0;
}
if is_key_down(KeyCode::Left) {
x -= 1.0;
}
if is_key_down(KeyCode::Down) {
y += 1.0;
}
if is_key_down(KeyCode::Up) {
y -= 1.0;
}
You can find other available keys in the documentation of KeyCode.
Draw a circle
Finally we will draw a circle on the screen at the coordinates in x
and y
.
The circle has a radius of 16 and will be drawn in a yellow color.
draw_circle(x, y, 16.0, YELLOW);
Source
The source of main.rs
should look like this:
use macroquad::prelude::*;
#[macroquad::main("My game")]
async fn main() {
let mut x = screen_width() / 2.0;
let mut y = screen_height() / 2.0;
loop {
clear_background(DARKPURPLE);
if is_key_down(KeyCode::Right) {
x += 1.0;
}
if is_key_down(KeyCode::Left) {
x -= 1.0;
}
if is_key_down(KeyCode::Down) {
y += 1.0;
}
if is_key_down(KeyCode::Up) {
y -= 1.0;
}
draw_circle(x, y, 16.0, YELLOW);
next_frame().await
}
}
When you run the game, a yellow circle will appear in the middle of the window. Try using the arrow keys to move the circle around.