Skip to content

Instantly share code, notes, and snippets.

@honix
Last active January 29, 2019 13:10
Show Gist options
  • Save honix/0196f3ec62623dd28fcb0c34ed668724 to your computer and use it in GitHub Desktop.
Save honix/0196f3ec62623dd28fcb0c34ed668724 to your computer and use it in GitHub Desktop.
SCRIPT-8
const { pow } = Math
const gravity = 10 * 0.01,
damp = 0.99,
speed = 100 * 0.01
initialState = {
balls: [
{
x: 64,
y: 120,
ax: 7,
ay: 1,
size: 3
},
{
x: 120,
y: 64,
ax: -4,
ay: -5,
size: 5
},
{
x: 8,
y: 64,
ax: -2,
ay: -2,
size: 7
}
],
time: 0
}
let updateBall = (ball) => {
let x = ball.x + ball.ax * speed,
y = ball.y + ball.ay * speed,
offX = x < ball.size || x > 128 - ball.size,
offY = y < ball.size || y > 128 - ball.size
return {
x: x,
y: y,
ax: offX ? -ball.ax : ball.ax * damp,
ay: offY ? -ball.ay : ball.ay * damp + gravity,
size: ball.size
}
}
let constDist = (ball, others) => {
let shiftx = 0,
shifty = 0
others.forEach(other => {
let dx = ball.x - other.x,
dy = ball.y - other.y,
dist = pow(pow(dx, 2) + pow(dy, 2), -2),
nx = dx / dist,
ny = dy / dist
shiftx += nx
shifty += ny
})
shiftx = shiftx / others.length * 0.01
shifty = shifty / others.length * 0.01
return {
x: ball.x,
y: ball.y,
ax: ball.ax,
ay: ball.ay,
size: ball.size
}
}
update = (state, input, elapsed) => {
state.time += elapsed
state.balls = state.balls
.map(b => updateBall(b))
.map(b => constDist(b, state.balls))
}
let printTime = (state) => {
let t = state.time
t = t / 1000
t = t - t % 1
print(0, 0, t, 2)
}
draw = (state) => {
clear()
rectFill(0, 0, 128, 128, 6)
state.balls.forEach(b => {
circFill(b.x, b.y, b.size)
state.balls.forEach(ob => {
line(b.x, b.y, ob.x, ob.y, 4)
})
})
printTime(state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment