diff options
Diffstat (limited to 'examples/noc/src/pendulum.zig')
| -rw-r--r-- | examples/noc/src/pendulum.zig | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/examples/noc/src/pendulum.zig b/examples/noc/src/pendulum.zig new file mode 100644 index 0000000..0ea177f --- /dev/null +++ b/examples/noc/src/pendulum.zig @@ -0,0 +1,54 @@ +//! Nature of Code, Example 3.11: Swinging Pendulum. Drag the bob. +const std = @import("std"); +const sk = @import("sketch"); +const vec = sk.math; + +pub const name = "pendulum"; +pub const width = 640; +pub const height = 360; + +const pivot: vec.Vec = .{ width / 2, 30 }; +const r = 175; +const ball_r = 24; +const damping = 0.995; +const gravity = 0.4; + +pub const State = struct { + angle: f32 = std.math.pi / 4.0, + angle_velocity: f32 = 0, + dragging: bool = false, + clock: sk.Clock = .{}, + + fn bob(s: *const State) vec.Vec { + return pivot + vec.scale(.{ @sin(s.angle), @cos(s.angle) }, r); + } +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (in.events) |e| switch (e.kind) { + .mouse_down => if (vec.distance(.{ e.x, e.y }, s.bob()) < ball_r) { + s.dragging = true; + }, + .mouse_up => { + s.angle_velocity = 0; + s.dragging = false; + }, + else => {}, + }; + for (0..s.clock.steps(in)) |_| if (s.dragging) { + const diff = pivot - vec.Vec{ in.mouse_x, in.mouse_y }; + s.angle = std.math.atan2(-diff[1], diff[0]) - std.math.degreesToRadians(90); + } else { + s.angle_velocity += -gravity / @as(f32, r) * @sin(s.angle); + s.angle += s.angle_velocity; + s.angle_velocity *= damping; + }; +} + +const pen: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 }; + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(sk.Color.white); + sk.draw.line(f, pivot, s.bob(), pen); + sk.draw.circle(f, s.bob(), ball_r, pen); +} |
