//! Example 3.2: Forces with (arbitrary) angular motion. Twenty movers orbit //! an attractor and spin with their sideways acceleration. const std = @import("std"); const sk = @import("sketch"); const vec = sk.math; pub const name = "angular_forces"; pub const width = 640; pub const height = 360; const Mover = struct { mass: f32 = 1, radius: f32 = 8, position: vec.Vec = .{ 0, 0 }, velocity: vec.Vec = .{ 0, 0 }, acceleration: vec.Vec = .{ 0, 0 }, angle: f32 = 0, angle_velocity: f32 = 0, angle_acceleration: f32 = 0, fn applyForce(m: *Mover, force: vec.Vec) void { m.acceleration += vec.scale(force, 1 / m.mass); } fn update(m: *Mover) void { m.velocity += m.acceleration; m.position += m.velocity; m.angle_acceleration = m.acceleration[0] / 10.0; m.angle_velocity = std.math.clamp(m.angle_velocity + m.angle_acceleration, -0.1, 0.1); m.angle += m.angle_velocity; m.acceleration = .{ 0, 0 }; } }; const Attractor = struct { position: vec.Vec = .{ width / 2, height / 2 }, mass: f32 = 20, g: f32 = 1, fn attract(a: Attractor, m: Mover) vec.Vec { const force = a.position - m.position; const distance = std.math.clamp(vec.length(force), 5, 25); return vec.withLength(force, (a.g * a.mass * m.mass) / (distance * distance)); } }; const attractor: Attractor = .{}; pub const State = struct { movers: [20]Mover = @splat(.{}), rng: std.Random.Xoshiro256 = .init(32), clock: sk.Clock = .{}, }; pub fn init(s: *State) void { const r = s.rng.random(); for (&s.movers) |*m| { const position: vec.Vec = .{ std.math.lerp(0, width, r.float(f32)), std.math.lerp(0, height, r.float(f32)) }; const mass = std.math.lerp(0.1, 2, r.float(f32)); const velocity: vec.Vec = .{ std.math.lerp(-1, 1, r.float(f32)), std.math.lerp(-1, 1, r.float(f32)) }; m.* = .{ .mass = mass, .radius = mass * 8, .position = position, .velocity = velocity }; } } pub fn update(s: *State, in: *const sk.Input) void { for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| { m.applyForce(attractor.attract(m.*)); m.update(); }; } const attractor_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(175).alpha(200), .stroke = .black, .width = 2 }; const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 }; pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(sk.Color.white); sk.draw.circle(f, attractor.position, attractor.mass, attractor_pen); for (s.movers) |m| { const pen = mover_pen.transformed(.place(m.position, m.angle)); // push; translate; rotate sk.draw.circle(f, .{ 0, 0 }, m.radius, pen); sk.draw.line(f, .{ 0, 0 }, .{ m.radius, 0 }, pen); } }