Skip to content

Instantly share code, notes, and snippets.

@thykka
Last active July 1, 2020 19:39
Show Gist options
  • Select an option

  • Save thykka/e3bd0d167f50c2069f9a6ede563d6a51 to your computer and use it in GitHub Desktop.

Select an option

Save thykka/e3bd0d167f50c2069f9a6ede563d6a51 to your computer and use it in GitHub Desktop.
SCRIPT-8
// title: Clockwork
const { PI, sin, cos, max, round } = Math
init = state => {
state.time = 0
state.gears = [createGear({
color: 3,
x: 15,
y: 15,
radius: 14,
angle: 0,
teeth: 16,
speed: 2
})]
addGear(state, state.gears[0], {
radius: 24,
teeth: 32
}, 116)
addGear(state, state.gears[1], {
radius: 40,
teeth: 64,
}, 150)
addGear(state, state.gears[2], {
radius: 24,
teeth: 16,
}, 20)
addGear(state, state.gears[1], {
radius: 20,
teeth: 16,
}, 220)
addGear(state, state.gears[4], {
radius: 16,
teeth: 16,
}, 180)
}
function addGear(state, parent, gearOptions, offset = 0, byRadius = false) {
const [px, py] = parent.pos
const dist = parent.radius + gearOptions.radius
const offsetRad = offset / 180 * PI
const gx = px + sin(offsetRad) * dist
const gy = py - cos(offsetRad) * dist
const ratio = byRadius
? gearOptions.radius / parent.radius
: gearOptions.teeth / parent.teeth
const settings = Object.assign({
x: gx,
y: gy,
speed: -parent.speed / ratio,
angle: 0,//2*PI / ratio, // ????
color: parent.color + 1
}, gearOptions)
state.gears.push(createGear(settings))
}
function createGear({ x = 0, y = 0, radius = 8, teeth = 16, angle = 0, speed = PI / 4, color = 0 }) {
return {
color,
radius,
teeth,
pos: [x, y],
angle,
speed
}
}
update = (state, input, elapsed) => {
state.time += elapsed
state.elapsed = elapsed;
state.gears.forEach(gear => updateGear(gear, state))
}
function updateGear(gear, state) {
gear.angle += gear.speed * state.elapsed / 1000;
}
draw = state => {
clear()
state.gears.forEach(drawGear);
}
function drawGear(gear) {
const [cx, cy] = gear.pos.map(v => v - 0.5)
let ix, iy
circFill(cx, cy, max(gear.radius - 2, 0), gear.color)
range(0, gear.teeth).forEach(index => {
const tOffset = index / gear.teeth
const tx = sin(gear.angle + tOffset * PI * 2) * (gear.radius - 1);
const ty = -cos(gear.angle + tOffset * PI * 2) * (gear.radius - 1);
line(cx + tx * 0.875, cy + ty * 0.875, cx + tx, cy + ty, 7)
if(!index) {
ix = (cx + tx * 0.75)
iy = (cy + ty * 0.75)
}
})
circStroke(cx, cy, gear.radius, clamp(gear.color - 1, 0, 6))
line(cx, cy, ix, iy, clamp(gear.color - 2, 0, 7))
}
{
"iframeVersion": "0.1.280",
"lines": [
104,
0,
0,
0,
0,
0,
0,
0
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment