commit 7c9c4d12d7d6459804593ae1170777b6b3369b94
parent 4f60de7c89963bb3c965c63ade7c4f1eae1ee3a9
Author: brookjeynes <me@brookjeynes.dev>
Date: Thu, 30 Jul 2026 06:07:33 +1000
feat: add bullet collision
Signed-off-by: brookjeynes <me@brookjeynes.dev>
Diffstat:
2 files changed, 50 insertions(+), 10 deletions(-)
diff --git a/src/bullet.zig b/src/bullet.zig
@@ -1,7 +1,7 @@
const raylib = @import("raylib");
const Timer = @import("./timer.zig");
-const radius: f16 = 10.0;
+pub const radius: f16 = 10.0;
pub const Bullet = struct {
position: raylib.Vector2,
@@ -36,6 +36,14 @@ pub fn Pool(comptime upper: usize) type {
self.count += 1;
}
+ pub fn despawn(self: *Self, idx: usize) void {
+ for (idx..self.count) |i| {
+ self.bullets[i] = self.bullets[i + 1];
+ }
+
+ self.count -= 1;
+ }
+
pub fn render(self: *Self, screen_size: raylib.Vector2) void {
const delta = raylib.GetFrameTime();
@@ -50,11 +58,7 @@ pub fn Pool(comptime upper: usize) type {
bullet.position.y < -radius * 2 or
bullet.position.y > screen_size.y + radius * 2)
{
- for (i..self.count) |j| {
- self.bullets[j] = self.bullets[j + 1];
- }
-
- self.count -= 1;
+ self.despawn(i);
continue;
}
diff --git a/src/main.zig b/src/main.zig
@@ -3,7 +3,7 @@ const std = @import("std");
const raylib = @import("raylib");
const raymath = @import("raymath");
-const bullet = @import("./bullet.zig");
+const Bullet = @import("./bullet.zig");
const Enemy = @import("./enemy.zig");
const Player = @import("./player.zig");
const Timer = @import("./timer.zig");
@@ -25,7 +25,7 @@ pub fn main() !void {
},
};
- var enemy_spawn_time: Timer = .{ .duration = 0.2 };
+ var enemy_spawn_time: Timer = .{ .duration = 1 };
var enemies: [255]Enemy = undefined;
var enemy_count: u8 = 0;
@@ -54,8 +54,44 @@ pub fn main() !void {
raylib.ClearBackground(raylib.RAYWHITE);
player.render();
- for (0..enemy_count) |i| {
- enemies[i].render();
+
+ var enemy_idx: usize = 0;
+ while (enemy_idx < enemy_count) {
+ const enemy = &enemies[enemy_idx];
+
+ for (0..player.bullet_pool.count) |bullet_idx| {
+ const bullet = player.bullet_pool.bullets[bullet_idx];
+
+ const is_collision = raylib.CheckCollisionCircleRec(
+ .{
+ .x = bullet.position.x,
+ .y = bullet.position.y,
+ },
+ Bullet.radius,
+ .{
+ .x = enemy.position.x,
+ .y = enemy.position.y,
+ .width = enemy.size.x,
+ .height = enemy.size.y,
+ },
+ );
+
+ if (is_collision) {
+ player.bullet_pool.despawn(bullet_idx);
+
+ for (enemy_idx..enemy_count) |i| {
+ enemies[i] = enemies[i + 1];
+ }
+ enemy_count -= 1;
+ continue;
+ }
+ }
+
+ enemy_idx += 1;
+ }
+
+ for (0..enemy_count) |idx| {
+ enemies[idx].render();
}
}
}