const rl = @import("raylib"); const std = @import("std"); gamepad: i32 = 0, active: bool = false, last_hand_position: rl.Vector2 = rl.Vector2.zero(), mouse_hand_position: rl.Vector2 = rl.Vector2.zero(), const mouseHandRadius = 100.0; pub fn init() @This() { return @This(){}; } fn clampVector(vec: rl.Vector2) rl.Vector2 { if (vec.length2() > 1) { return vec.normalize(); } return vec; } fn getKeyboardWalkDirection() rl.Vector2 { var dx: f32 = 0; var dy: f32 = 0; if (rl.IsKeyDown(rl.KeyboardKey.KEY_W)) { dy -= 1; } if (rl.IsKeyDown(rl.KeyboardKey.KEY_S)) { dy += 1; } if (rl.IsKeyDown(rl.KeyboardKey.KEY_A)) { dx -= 1; } if (rl.IsKeyDown(rl.KeyboardKey.KEY_D)) { dx += 1; } return (rl.Vector2{ .x = dx, .y = dy }).normalize(); } fn getGamepadWalkDirection(gamepad: i32) ?rl.Vector2 { if (!rl.IsGamepadAvailable(gamepad)) { return null; } const x = rl.GetGamepadAxisMovement(gamepad, .GAMEPAD_AXIS_LEFT_X); const y = rl.GetGamepadAxisMovement(gamepad, .GAMEPAD_AXIS_LEFT_Y); if (@fabs(x) < 0.001 and @fabs(y) < 0.001) { return null; } return clampVector(.{ .x = x, .y = y }); } pub fn getWalkDirection(self: *@This()) rl.Vector2 { if (!self.active) { return rl.Vector2.zero(); } var walk_direction = getKeyboardWalkDirection(); if (getGamepadWalkDirection(self.gamepad)) |dir| { walk_direction = dir; } return walk_direction; } fn getGamepadHandPosition(gamepad: i32) ?rl.Vector2 { if (!rl.IsGamepadAvailable(gamepad)) { return null; } const x = rl.GetGamepadAxisMovement(gamepad, .GAMEPAD_AXIS_RIGHT_X); const y = rl.GetGamepadAxisMovement(gamepad, .GAMEPAD_AXIS_RIGHT_Y); if (@fabs(x) < 0.001 and @fabs(y) < 0.001) { return null; } return clampVector(.{ .x = x, .y = y }); } fn getMouseHandPosition(self: *@This()) rl.Vector2 { const mouse_delta = rl.GetMouseDelta(); self.mouse_hand_position = clampVector(self.mouse_hand_position.add(mouse_delta.scale(1.0/mouseHandRadius))); return self.mouse_hand_position; } pub fn getHandPosition(self: *@This()) rl.Vector2 { if (!self.active) { return self.last_hand_position; } var hand_position = self.getMouseHandPosition(); if (getGamepadHandPosition(self.gamepad)) |pos| { hand_position = pos; } self.last_hand_position = hand_position; return hand_position; } pub fn isPausePressed(self: *@This()) bool { if (rl.IsKeyPressed(rl.KeyboardKey.KEY_ESCAPE)) { return true; } if (rl.IsGamepadAvailable(self.gamepad) and rl.IsGamepadButtonPressed(self.gamepad, .GAMEPAD_BUTTON_MIDDLE_RIGHT)) { return true; } return false; } pub fn activate(self: *@This()) void { if (self.active) return; rl.DisableCursor(); self.active = true; } pub fn deactivate(self: *@This()) void { if (!self.active) return; rl.EnableCursor(); self.active = false; }