Created
November 11, 2023 12:04
-
-
Save peterhellberg/9597e1c5117a10cb600cfd35473767db to your computer and use it in GitHub Desktop.
Implementation of https://github.com/nesbox/TIC-80/wiki/Code-examples-and-snippets#draw-hanging-cable in Zig ⚡
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const math = @import("std").math; | |
const tic = @import("tic80.zig"); | |
fn drawCable(p1: [2]f32, p2: [2]f32, max_sag: f32, color: i32) [2]f32 { | |
const dx = p2[0] - p1[0]; | |
const dy = p2[1] - p1[1]; | |
const length = math.sqrt(dx * dx + dy * dy); | |
const sag = @max(length / max_sag, max_sag); | |
const midpoint: [2]f32 = .{ | |
(p1[0] + p2[0]) / 2, | |
(p1[1] + p2[1]) / 2 + sag, | |
}; | |
for (0..@as(usize, @intFromFloat(length))) |ux| { | |
const x: f32 = @floatFromInt(ux); | |
const y = math.sin(x / length * math.pi) * sag; | |
const px = p1[0] + dx * x / length + 0.5; | |
const py = p1[1] + dy * x / length + y + 0.5; | |
const px_prev = p1[0] + dx * (x - 1) / length + 0.5; | |
const py_prev = p1[1] + dy * (x - 1) / length + math.sin((x - 1) / length * math.pi) * sag + 0.5; | |
tic.line(px_prev, py_prev, px, py, color); | |
} | |
return midpoint; | |
} |
Author
peterhellberg
commented
Nov 11, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment