Base for left and right movement code.

This commit is contained in:
KikooDX 2021-01-27 17:23:45 +01:00
parent ab597a39ca
commit 497f1239e6
2 changed files with 72 additions and 2 deletions

View File

@ -4,11 +4,11 @@ const ray = @cImport({
const std = @import("std");
const assert = std.debug.assert;
const format = std.fmt.format;
const maxInt = std.math.maxInt;
const log = std.log.default.debug;
const Level = @import("level.zig");
const Vec2 = @import("vec2.zig");
const movement = @import("movement.zig");
pub fn main() !void {
// Create allocator
@ -49,7 +49,6 @@ pub fn main() !void {
while (key != 0) {
// Add key to buffer.
input_buffer[input_cursor] = @intCast(u32, key);
log("Key pressed: {}", .{key});
input_cursor += 1;
// Avoid writing out of memory.
if (input_cursor >= input_buffer_len)
@ -58,6 +57,21 @@ pub fn main() !void {
key = ray.GetCharPressed();
}
// Process buffer content.
// Read the buffer backwards. This is placeholder logic.
while (input_cursor > 0) {
input_cursor -= 1;
const action = input_buffer[input_cursor];
switch (action) {
'h' => movement.move_left(&camera, 1),
'j' => {},
'k' => {},
'l' => movement.move_right(&camera, 1),
else => log("No action mapped to this key.", .{}),
}
}
ray.BeginDrawing();
defer ray.EndDrawing();

56
src/movement.zig Normal file
View File

@ -0,0 +1,56 @@
//! Movement functions.
const std = @import("std");
const expect = std.testing.expect;
const maxInt = std.math.maxInt;
const Vec2 = @import("vec2.zig");
const maxIntVec2 = comptime maxInt(Vec2.int_type);
pub fn move_left(cursor: *Vec2, n: u64) void {
if (n > maxIntVec2) {
cursor.x = 0;
return;
}
const steps = @intCast(Vec2.int_type, n);
if (cursor.x >= steps)
cursor.x -= steps
else
cursor.x = 0;
}
pub fn move_right(cursor: *Vec2, n: u64) void {
if (n > maxIntVec2) {
cursor.x = maxIntVec2;
return;
}
const steps = @intCast(Vec2.int_type, n);
if (maxIntVec2 - cursor.x >= steps)
cursor.x += steps
else
cursor.x = maxIntVec2;
}
test "move left" {
var cursor = Vec2.init(42, 51);
move_left(&cursor, 2);
expect(cursor.x == 40);
move_left(&cursor, 38);
expect(cursor.x == 2);
move_left(&cursor, 7548748948487);
expect(cursor.x == 0);
}
test "move right" {
var cursor = Vec2.init(564, 42);
move_right(&cursor, 51);
expect(cursor.x == 615);
move_right(&cursor, 51204758045045);
expect(cursor.x == maxIntVec2);
}