Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An example in orbiting bodies in ClojureScript with big-bang, inspired by a 'Translation and Rotation in 2D and 3D' tutorial by David Meredith, Aalborg University
(ns big-bang.examples.solar-system
(:require
[big-bang.core :refer [big-bang]]
[big-bang.components :refer [dropdown slider color-picker]]
[enchilada :refer [ctx canvas canvas-size proxy-request]]
[monet.canvas :refer [circle fill fill-style stroke-style stroke
clear-rect save restore translate rotate]]
[jayq.core :refer [show]]))
(def width (first (canvas-size)))
(def height (second (canvas-size)))
(defn deg->rad [x]
(/ (* x Math/PI) 180.0))
(def initial-state {
:sun {
:translate [(/ width 2) (/ height 2)]
:size 20
:color :yellow
:theta 0.0
:earth {
:translate [80 0]
:size 10
:color :blue
:speed (deg->rad 1.0)
:theta 0.0
:moon {
:translate [20 0]
:size 4
:color :blue
:speed (deg->rad -2.0)
:theta 0.0}}
:mars {
:translate [150 0]
:size 7
:color :red
:speed (deg->rad 3.0)
:theta 0.0
:moon {
:deimus {
:translate [30 0]
:size 3
:color :red
:speed (deg->rad -4.0)
:theta 0.0}
:phobos {
:translate [20 0]
:size 3
:color :red
:speed (deg->rad 5.0)
:theta 0.0}}}}})
(defn update-theta [m ks]
(let [speed (get-in m (conj ks :speed))]
(update-in m (conj ks :theta) + speed)))
(defn update-state [event world-state]
(->
world-state
(update-theta [:sun :earth])
(update-theta [:sun :earth :moon])
(update-theta [:sun :mars])
(update-theta [:sun :mars :moon :deimus])
(update-theta [:sun :mars :moon :phobos])))
(defn render-object [ctx root ks]
(let [m (get-in root ks)]
(->
ctx
(rotate (:theta m))
(translate (first (:translate m)) (second (:translate m)))
(fill-style (:color m))
(circle {:x 0 :y 0 :r (:size m)})
(fill)
(stroke-style :black)
(stroke))))
(defn render-system [world-state]
(->
ctx
(clear-rect {:x 0 :y 0 :w width :h height})
(save)
(render-object world-state [:sun])
(save)
(render-object world-state [:sun :earth])
(save)
(render-object world-state [:sun :earth :moon])
(restore)
(restore)
(save)
(render-object world-state [:sun :mars])
(save)
(render-object world-state [:sun :mars :moon :deimus])
(restore)
(save)
(render-object world-state [:sun :mars :moon :phobos])
(restore)
(restore)
(restore)))
(show canvas)
(big-bang
:initial-state initial-state
:on-tick update-state
:to-draw render-system)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment