Last active
December 30, 2015 07:59
-
-
Save saolsen/7799393 to your computer and use it in GitHub Desktop.
particle simulation
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
(ns saolsen.particles-simulate | |
(:require [saolsen.draw-2d :as draw])) | |
;; Simple simulated neutonian physics. | |
(defn integrate-particle | |
"Moves the particle a distance based on it's velocity | |
P = P + V*dt | |
Simple collisions with walls reverse velocity. | |
Returns a new particle. | |
" | |
[world-width world-height particle] | |
(let [pos (:pos particle) | |
vel (:vel particle) | |
new-pos (map + pos (map #(* 0.1 %) vel)) | |
[nx ny] new-pos | |
collisions (cond | |
(or (< nx 0) (> nx world-width)) [-1 1] | |
(or (< ny 0) (> ny world-height)) [1 -1] | |
:else [1 1]) | |
new-vel (map * vel collisions)] | |
(assoc particle :pos new-pos :vel new-vel))) | |
(defn main [] | |
(let [context (draw/get-canvas-context-from-id "draw") | |
border {:type :line | |
:color [0 0 0] | |
:posns [[0 0] [500 0] [500 500] [0 500]] | |
:width 5} | |
span (take 6 (iterate (partial + 100) 40)) | |
particles (for [x span | |
y span] | |
{:type :circle | |
:color [0 200 200] | |
:pos [x y] | |
:vel [(- (rand-int 100) 50) | |
(- (rand-int 100) 50)] | |
:size 5}) | |
integrater (partial integrate-particle | |
(:width context) | |
(:height context)) | |
worldstate (atom particles)] | |
(defn update [] | |
(draw/request-animation-frame update) | |
(swap! worldstate (partial map integrater)) | |
(draw/draw-scene (cons border @worldstate) context)) | |
(update))) | |
(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment