grunt.zig (2017B)
1 const raylib = @import("raylib"); 2 const raymath = @import("raymath"); 3 4 const bullet = @import("../bullet.zig"); 5 const constants = @import("../constants.zig"); 6 7 pub const size: raylib.Vector2 = .{ .x = 40, .y = 40 }; 8 9 pub const Grunt = @This(); 10 11 movement_speed: f32 = 40.0, 12 bullet_speed: f32 = 100.0, 13 direction: raylib.Vector2 = .{}, 14 position: raylib.Vector2 = .{}, 15 health: f32 = constants.grunt_health, 16 17 bullet_pool: bullet.Pool, 18 19 pub fn tick(self: *Grunt) void { 20 if (self.bullet_pool.tick()) self.shoot(); 21 } 22 23 pub fn shoot(self: *Grunt) void { 24 self.bullet_pool.spawn( 25 .{ 26 .x = self.position.x + (size.x / 2), 27 .y = self.position.y + (size.y / 2), 28 }, 29 .{ 30 .x = self.direction.x * self.bullet_speed, 31 .y = self.direction.y * self.bullet_speed, 32 }, 33 raylib.RED, 34 constants.grunt_bullet_damage, 35 ); 36 } 37 38 pub fn handleMovement(self: *Grunt, target: raylib.Vector2) void { 39 const delta: f32 = raylib.GetFrameTime(); 40 41 const direction: raymath.Vector2 = raymath.Vector2Subtract(@bitCast(target), @bitCast(self.position)); 42 self.direction = @bitCast(raymath.Vector2Normalize(@bitCast(direction))); 43 self.position.x += self.direction.x * self.movement_speed * delta; 44 self.position.y += self.direction.y * self.movement_speed * delta; 45 46 const max_x: f32 = @as(f32, @floatFromInt(raylib.GetScreenWidth())) - size.x; 47 const max_y: f32 = @as(f32, @floatFromInt(raylib.GetScreenHeight())) - size.y; 48 self.position.x = @max(0, @min(max_x, self.position.x)); 49 self.position.y = @max(0, @min(max_y, self.position.y)); 50 } 51 52 pub fn handleDamage(self: *Grunt, damage: f32) bool { 53 self.health -= damage; 54 return self.health <= 0; 55 } 56 57 pub fn render(self: *Grunt) void { 58 raylib.DrawRectangleV( 59 self.position, 60 size, 61 raylib.RED, 62 ); 63 64 self.bullet_pool.render(.{ 65 .x = @floatFromInt(raylib.GetScreenWidth()), 66 .y = @floatFromInt(raylib.GetScreenHeight()), 67 }); 68 }