bullet.zig (2193B)
1 const std = @import("std"); 2 3 const raylib = @import("raylib"); 4 5 const constants = @import("./constants.zig"); 6 const Timer = @import("./timer.zig"); 7 8 pub const radius: f32 = 10.0; 9 10 pub const Bullet = struct { 11 position: raylib.Vector2, 12 velocity: raylib.Vector2, 13 color: raylib.Color, 14 damage: f32, 15 }; 16 17 pub const Pool = struct { 18 bullets: [constants.max_bullets]Bullet, 19 count: usize = 0, 20 fire_timer: Timer, 21 22 pub fn tick(self: *Pool) bool { 23 return self.fire_timer.tick(raylib.GetFrameTime()); 24 } 25 26 pub fn spawn( 27 self: *Pool, 28 position: raylib.Vector2, 29 velocity: raylib.Vector2, 30 colour: raylib.Color, 31 damage: f32, 32 ) void { 33 if (self.count == self.bullets.len) return; 34 self.bullets[self.count] = .{ 35 .position = position, 36 .velocity = velocity, 37 .color = colour, 38 .damage = damage, 39 }; 40 self.count += 1; 41 } 42 43 pub fn despawn(self: *Pool, idx: usize) void { 44 for (idx..self.count - 1) |i| { 45 self.bullets[i] = self.bullets[i + 1]; 46 } 47 48 if (self.count > 0) self.count -= 1; 49 } 50 51 pub fn render(self: *Pool, screen_size: raylib.Vector2) void { 52 const delta = raylib.GetFrameTime(); 53 54 var i: usize = 0; 55 while (i < self.count) { 56 var bullet = &self.bullets[i]; 57 bullet.position.x += bullet.velocity.x * delta; 58 bullet.position.y += bullet.velocity.y * delta; 59 60 if (bullet.position.x < -radius * 2 or 61 bullet.position.x > screen_size.x + radius * 2 or 62 bullet.position.y < -radius * 2 or 63 bullet.position.y > screen_size.y + radius * 2) 64 { 65 self.despawn(i); 66 continue; 67 } 68 69 raylib.DrawCircleV(bullet.position, radius, bullet.color); 70 71 i += 1; 72 } 73 } 74 75 pub fn transferFrom(self: *Pool, src: *Pool) void { 76 const n = @min(src.count, self.bullets.len - self.count); 77 @memcpy(self.bullets[self.count .. self.count + n], src.bullets[0..n]); 78 self.count += n; 79 src.count = 0; 80 } 81 };