summaryrefslogtreecommitdiff
path: root/examples/noc/src/pendulum.zig
blob: 0ea177fa06afd49ecd8aa6a66c084597aab4d340 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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);
}