(ns lab.collisions [:require [quil.core :refer :all] [quil.middleware :as m]]) (def quant 7) (def the-w 600) (def the-h 400) (def margin-l (+ 0 50)) (def margin-r (- the-w 50)) (def margin-u (+ 0 50)) (def margin-d (- the-h 50)) (defn rand-lower-upper [lower upper] (+ lower (rand (- upper lower)))) (defn generate-sprite [] (hash-map :x (rand-lower-upper margin-l margin-r) :y (rand-lower-upper margin-u margin-d) :dx (rand-lower-upper -1.0 1.0) :dy (rand-lower-upper -1.0 1.0) :r (rand-int 256) :g (rand-int 256) :b (rand-int 256) :v (rand 4))) (defn setup [] (frame-rate 60) (take quant (repeatedly generate-sprite))) (defn move [{:keys [dx dy v] :as sprite}] (-> sprite (update-in [:x] + (* v dx)) (update-in [:y] + (* v dy)))) (defn bounce [{:keys [x y dx dy] :as sprite}] (let [fx (if (or (and (< x margin-l) (neg? dx)) (and (> x margin-r) (pos? dx))) -1 1) fy (if (or (and (< y margin-u) (neg? dy)) (and (> y margin-d) (pos? dy))) -1 1)] (-> sprite (update-in [:dx] * fx) (update-in [:dy] * fy)))) ; alternate behavior to bounce : when sprite touches wall, it disappears and appears in the other side (defn pass [{:keys [x y dx dy] :as sprite}] (let [mrgn-l (if (and (< x margin-l) (neg? dx)) (assoc sprite :x margin-r) sprite) mrgn-r (if (and (> x margin-r) (pos? dx)) (assoc mrgn-l :x margin-l) mrgn-l) mrgn-u (if (and (< y margin-u) (neg? dy)) (assoc mrgn-r :y margin-d) mrgn-r) mrgn-d (if (and (> y margin-d) (pos? dy)) (assoc mrgn-u :y margin-u) mrgn-u)] mrgn-d)) (defn my-update [state] (map (comp move bounce) state)) (defn draw-sprite [{:keys [x y r g b]}] (fill r g b) (rect (- x 15) (- y 15) 30 30)) (defn draw [state] (background 200 150 255) (dorun (map draw-sprite state))) (defsketch collision :title "Colisões" :size [the-w the-h] :setup setup :draw draw :update my-update :middleware [m/fun-mode])