Download

← Examples

raylib_sprite

A window and a sprite that the arrow keys move, through raylib.

examples/raylib_sprite in the repository.

// examples/raylib_sprite: a window, and a sprite the arrow keys move: Vader's
// logo (`editors/common/vader.svg`), drawn at 64 pixels.
//
//   vader build examples/raylib_sprite
//   ./examples/raylib_sprite/build/debug-<os>-<arch>/raylib_sprite
//
// `sprite.png` is baked into the program (`@comptime`), so the executable needs no
// file beside it, and `vader run examples/raylib_sprite` runs it on the
// interpreter, through adapters it compiles with `cc`. raylib comes from the
// toolchain's `third_party/` folder, which `vader.json` names.

module "main"

import "raylib"
import "std/abort"
import "std/io"
import "std/math"

/// The sprite's PNG, read when the program is compiled.
SPRITE :: @comptime {
    read :: read_file_bytes("sprite.png")
    if read is IOError {
        panic("cannot read `sprite.png`: ${read.message()}")
    }
    return read
}

SCREEN_WIDTH: i32: 800
SCREEN_HEIGHT: i32: 450
/// Sprite speed, in pixels per second.
SPEED: f32: 240.0

main :: fn() -> i32 {
    init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Vader + raylib")
    defer close_window()
    set_target_fps(60)
    sprite :: load_texture_from_memory(".png", SPRITE)
    // raylib only logs the failure among its own lines.
    if sprite == null {
        eprintln("cannot decode sprite.png")
        return 1
    }
    defer unload_texture(sprite)
    max_x :: f32(SCREEN_WIDTH - sprite.width)
    max_y :: f32(SCREEN_HEIGHT - sprite.height)
    position :: Vector2 { .x = max_x / 2.0, .y = max_y / 2.0 }
    for !window_should_close() {
        step :: SPEED * get_frame_time()
        if is_key_down(.Right) { position.x += step }
        if is_key_down(.Left)  { position.x -= step }
        if is_key_down(.Down)  { position.y += step }
        if is_key_down(.Up)    { position.y -= step }
        position.x = clamp(position.x, 0.0, max_x)
        position.y = clamp(position.y, 0.0, max_y)
        begin_drawing()
        clear_background(RAYWHITE)
        draw_texture_v(sprite, position, WHITE)
        draw_text("Move the sprite with the arrow keys", 10, 10, 20, DARKGRAY)
        draw_fps(10, 40)
        end_drawing()
    }
    return 0
}