Skip to content

Instantly share code, notes, and snippets.

@quangIO
Created August 6, 2019 14:45
Show Gist options
  • Save quangIO/054edc7ccf1535507be2d98602c439a1 to your computer and use it in GitHub Desktop.
Save quangIO/054edc7ccf1535507be2d98602c439a1 to your computer and use it in GitHub Desktop.
import dom
import html5_canvas
import colors
import math
proc requestAnimationFrame(function: proc()) {.inline.} =
{.emit: ["requestAnimationFrame(", function, ");"].}
type
Vec2d = ref object
x, y: float
Particle = object #of RootObj
pos: Vec2d
vel: Vec2d
mass: float
proc updateForce(self: Particle, other: Particle) {.inline.} =
let
dx = other.pos.x - self.pos.x
dy = other.pos.y - self.pos.y
distSq = dx * dx + dy * dy
dist = sqrt(distSq)
F = self.mass * other.mass / distSq
self.vel.x += dx / dist * F * other.mass
self.vel.y += dy / dist * F * other.mass
other.vel.x -= dx / dist * F * self.mass
other.vel.y -= dy / dist * F * self.mass
proc update(self: Particle, ms: float) {.inline.} =
self.pos.x += self.vel.x * ms
self.pos.y += self.vel.y * ms
var
spaces: seq[Particle]
let
canvas = dom.document.getElementById("canvas-planet")
ctx = canvas.Canvas.getContext2D()
proc drawTest(x: float, y: float, r: float) {.inline.} =
ctx.fillStyle = "orange"
#ctx.shadowBlur = 75
ctx.beginPath()
ctx.arc(x mod 1900, y mod 1000, r, 0, 2 * PI, false)
ctx.fill()
proc uiLoop() =
ctx.clearRect(0, 0, 1900, 1000)
for i in 0..<spaces.len:
for j in i+1..<spaces.len:
updateForce(spaces[i], spaces[j])
spaces[i].update(1)
drawTest(spaces[i].pos.x, spaces[i].pos.y, 10.0)
#paces[spaces.len - 1].update(1)
#rawTest(spaces[spaces.len - 1].pos.x, spaces[spaces.len - 1].pos.y, 10.0)
requestAnimationFrame(uiLoop)
dom.window.onload = proc(e: dom.Event) =
spaces.add(Particle(pos: Vec2d(x: 30.0, y: 30.0), vel: Vec2d(x: 1.0, y: 0.0), mass:10))
spaces.add(Particle(pos: Vec2d(x: 200.0, y: 500.0), vel: Vec2d(x: 0.0, y: 0.0), mass:15))
#spaces.add(Particle(pos: Vec2d(x: 900.0, y: 100.0), vel: Vec2d(x: -2.0, y: 0.2), mass:10))
#spaces.add(Particle(pos: Vec2d(x: 1700.0, y: 800.0), vel: Vec2d(x: 0.0, y: 0.0), mass:25))
echo "STARTED"
uiLoop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment