blorb.zig (3026B)
1 const std = @import("std"); 2 3 const raylib = @import("raylib"); 4 5 const bullet = @import("../bullet.zig"); 6 const constants = @import("../constants.zig"); 7 8 pub const size: raylib.Vector2 = .{ .x = 60, .y = 60 }; 9 10 pub const Blorb = @This(); 11 12 movement_speed: f32 = 20.0, 13 bullet_speed: f32 = 50.0, 14 direction: raylib.Vector2 = .{}, 15 position: raylib.Vector2 = .{}, 16 shoot_offset: u2 = 0, 17 health: f32 = constants.blorb_health, 18 19 bullet_pool: bullet.Pool, 20 21 pub fn tick(self: *Blorb) void { 22 if (self.bullet_pool.tick()) self.shoot(); 23 } 24 25 pub fn shoot(self: *Blorb) void { 26 const center: raylib.Vector2 = .{ 27 .x = self.position.x + (size.x / 2), 28 .y = self.position.y + (size.y / 2), 29 }; 30 31 for ([_]u2{ 0, 1, 2, 3 }) |delta| { 32 const side = self.shoot_offset +% delta; 33 const spawn_position: raylib.Vector2 = switch (side) { 34 0 => .{ .x = center.x, .y = self.position.y }, 35 1 => .{ .x = self.position.x + size.x, .y = center.y }, 36 2 => .{ .x = center.x, .y = self.position.y + size.y }, 37 else => .{ .x = self.position.x, .y = center.y }, 38 }; 39 const bullet_velocity: raylib.Vector2 = switch (side) { 40 0 => .{ .x = 0, .y = -self.bullet_speed }, 41 1 => .{ .x = self.bullet_speed, .y = 0 }, 42 2 => .{ .x = 0, .y = self.bullet_speed }, 43 else => .{ .x = -self.bullet_speed, .y = 0 }, 44 }; 45 self.bullet_pool.spawn( 46 spawn_position, 47 bullet_velocity, 48 raylib.PURPLE, 49 constants.blorb_bullet_damage, 50 ); 51 } 52 53 self.shoot_offset +%= 1; 54 } 55 56 pub fn setRandomDirection(self: *Blorb) void { 57 const angle: f32 = @as(f32, @floatFromInt(raylib.GetRandomValue(0, 360))); 58 self.direction = .{ 59 .x = @cos(angle * std.math.pi / 180.0), 60 .y = @sin(angle * std.math.pi / 180.0), 61 }; 62 } 63 64 pub fn handleDamage(self: *Blorb, damage: f32) bool { 65 self.health -= damage; 66 return self.health <= 0; 67 } 68 69 pub fn handleMovement(self: *Blorb) void { 70 const delta: f32 = raylib.GetFrameTime(); 71 72 self.position.x += self.direction.x * self.movement_speed * delta; 73 self.position.y += self.direction.y * self.movement_speed * delta; 74 75 const max_x: f32 = @as(f32, @floatFromInt(raylib.GetScreenWidth())) - size.x; 76 const max_y: f32 = @as(f32, @floatFromInt(raylib.GetScreenHeight())) - size.y; 77 78 if (self.position.x <= 0 or self.position.x >= max_x) { 79 self.direction.x = -self.direction.x; 80 self.position.x = @max(0, @min(max_x, self.position.x)); 81 } 82 if (self.position.y <= 0 or self.position.y >= max_y) { 83 self.direction.y = -self.direction.y; 84 self.position.y = @max(0, @min(max_y, self.position.y)); 85 } 86 } 87 88 pub fn render(self: *Blorb) void { 89 raylib.DrawRectangleV( 90 self.position, 91 size, 92 raylib.PURPLE, 93 ); 94 95 self.bullet_pool.render(.{ 96 .x = @floatFromInt(raylib.GetScreenWidth()), 97 .y = @floatFromInt(raylib.GetScreenHeight()), 98 }); 99 }