summaryrefslogtreecommitdiff
path: root/examples/pen.zig
blob: acbd236dc5cbec27a98935e1b96bf9f5c0f2d93d (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
//! The drawing layer's convenience level: a ball that chases the mouse,
//! and three spinners around it, drawn with `sk.draw` and plain-data Pens.
//! Stepped at a fixed 60 Hz by `sk.Clock`, so a replay matches.
const std = @import("std");
const sk = @import("sketch");
const vec = sk.math;

pub const name = "pen";
pub const width = 640;
pub const height = 360;

pub const State = struct {
    position: vec.Vec = .{ width / 2, height / 2 },
    velocity: vec.Vec = .{ 0, 0 },
    spin: f32 = 0,
    clock: sk.Clock = .{ .hz = 60 },
};

pub fn update(s: *State, in: *const sk.Input) void {
    for (0..s.clock.steps(in)) |_| {
        const mouse: vec.Vec = .{ in.mouse_x, in.mouse_y };
        s.velocity = vec.clampLength(s.velocity + vec.withLength(mouse - s.position, 0.2), 5);
        s.position += s.velocity;
        s.spin += 0.03;
    }
}

const ball: sk.draw.Pen = .{ .fill = .gray(127), .stroke = .black, .width = 2 };
const spinner: sk.draw.Pen = .{ .fill = sk.Color.gray(200).alpha(160), .stroke = .black, .width = 2 };

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(sk.Color.white);
    sk.draw.circle(f, s.position, 24, ball);
    for (0..3) |i| {
        const turn = s.spin + @as(f32, @floatFromInt(i)) * 2 * std.math.pi / 3.0;
        // Push, translate, rotate: a copy of the pen, placed.
        const pen = spinner.transformed(.place(s.position + vec.scale(vec.unit(turn), 60), turn));
        sk.draw.circle(f, .{ 0, 0 }, 12, pen);
        sk.draw.line(f, .{ 0, 0 }, .{ 12, 0 }, pen);
        sk.draw.polygon(f, &.{ .{ 18, 0 }, .{ 14, -4 }, .{ 14, 4 } }, pen);
    }
    f.print(8, 8, 1, 0x000000, "steps {d}", .{s.clock.count});
}