Implement input handler

This commit is contained in:
Dusk 2023-09-22 14:03:33 +02:00
parent bdf4e0b920
commit 82e8cfdbe1
2 changed files with 54 additions and 0 deletions

32
src/input.zig Normal file
View File

@ -0,0 +1,32 @@
const rl = @import("raylib.zig");
const Input = struct {
name: []const u8,
code: i32,
default: i32,
pub fn isDown(self: Input) bool {
return rl.isKeyDown(self.code);
}
pub fn isJustPressed(self: Input) bool {
return rl.isKeyPressed(self.code);
}
pub fn isJustReleased(self: Input) bool {
return rl.isKeyReleased(self.code);
}
};
fn init(comptime name: []const u8, comptime key_code: []const u8) Input {
return Input{
.name = name,
.code = rl.getKeyCode(key_code),
.default = rl.getKeyCode(key_code),
};
}
pub const menu_left = init("Menu Left", "LEFT");
pub const menu_right = init("Menu Right", "RIGHT");
pub const menu_down = init("Menu Down", "DOWN");
pub const menu_up = init("Menu Up", "UP");
pub const menu_accept = init("Menu Accept", "ENTER");
pub const menu_cancel = init("Menu Cancel", "BACKSPACE");

View File

@ -27,6 +27,28 @@ pub fn endDrawing() void {
c.EndDrawing();
}
pub fn getKeyCode(comptime name: []const u8) i32 {
const full_name = "KEY_" ++ name;
if (!@hasDecl(c, full_name)) {
@compileError(full_name ++ " keycode does not exist.");
}
return @field(c, full_name);
}
pub fn isKeyPressed(key: i32) bool {
return c.IsKeyPressed(key);
}
pub fn isKeyDown(key: i32) bool {
return c.IsKeyDown(key);
}
pub fn isKeyReleased(key: i32) bool {
return c.IsKeyReleased(key);
}
pub fn drawText(text: [*c]const u8, x: i32, y: i32, fontSize: i32, color: [4]u8) void {
c.DrawText(text, x, y, fontSize, .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] });
}