utils.zig 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const std = @import("std");
  2. const math = std.math;
  3. const assert = std.debug.assert;
  4. pub const Vector2D = struct {
  5. x: f32,
  6. y: f32,
  7. const Self = @This();
  8. pub fn init(x: f32, y: f32) Self {
  9. return .{
  10. .x = x,
  11. .y = y,
  12. };
  13. }
  14. pub inline fn magnitude(self: Self) f32 {
  15. return math.sqrt(self.x * self.x + self.y * self.y);
  16. }
  17. pub fn unitVector(self: Self) Self {
  18. const r = self.magnitude();
  19. return .{
  20. .x = self.x / r,
  21. .y = self.y / r,
  22. };
  23. }
  24. pub inline fn displacement(vf: Self, vi: Self) Self {
  25. return .{
  26. .x = vf.x - vi.x,
  27. .y = vf.y - vi.y,
  28. };
  29. }
  30. pub inline fn direction(vf: Self, vi: Self) Self {
  31. return vf.displacement(vi).unitVector();
  32. }
  33. pub inline fn distance(vf: Self, vi: Self) f32 {
  34. return vf.displacement(vi).magnitude();
  35. }
  36. pub fn scalarMultiply(self: Self, scalar: f32) Self {
  37. return .{
  38. .x = self.x * scalar,
  39. .y = self.y * scalar,
  40. };
  41. }
  42. pub fn vectorAdd(self: Self, vector: Self) Self {
  43. return .{
  44. .x = self.x + vector.x,
  45. .y = self.y + vector.y,
  46. };
  47. }
  48. };
  49. pub const RGBColor = struct {
  50. r: u8,
  51. g: u8,
  52. b: u8,
  53. a: f32 = 1.0,
  54. const Self = @This();
  55. pub fn init(r: u8, g: u8, b: u8) Self {
  56. return .{
  57. .r = r,
  58. .g = g,
  59. .b = b,
  60. };
  61. }
  62. pub fn setAlpha(self: *Self, a: f32) void {
  63. assert(0.0 <= a and a <= 1.0);
  64. self.a = a;
  65. }
  66. };
  67. pub const Ball2D = struct {
  68. pos: Vector2D,
  69. vel: Vector2D,
  70. radius: f32,
  71. color: RGBColor,
  72. const Self = @This();
  73. pub fn init(pos: Vector2D, vel: Vector2D, radius: f32, color: RGBColor) Self {
  74. assert(0.0 <= radius);
  75. return .{
  76. .pos = pos,
  77. .vel = vel,
  78. .radius = radius,
  79. .color = color,
  80. };
  81. }
  82. pub fn collision(ball1: Self, ball2: Self) bool {
  83. const distance = Vector2D.distance(ball1.pos, ball2.pos);
  84. return distance < (ball1.radius + ball2.radius);
  85. }
  86. };