Last active
August 29, 2015 14:16
-
-
Save sroccaserra/20c0245f35c9727bdb94 to your computer and use it in GitHub Desktop.
Bouncing circle in Elm, try it here: http://elm-lang.org/try
This file contains hidden or 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
| import Color exposing (red) | |
| import Graphics.Collage exposing (circle, collage, Form, filled, move) | |
| import Graphics.Element exposing (Element) | |
| import List exposing (repeat) | |
| import Signal exposing (Signal, (<~), foldp) | |
| import Time exposing (fps) | |
| w : Float | |
| w = 500 | |
| h : Float | |
| h = 500 | |
| type alias Point a = {a | x: Float, y: Float} | |
| type alias Moving a = {a | vx: Float, vy: Float} | |
| update : Float -> Moving (Point a) -> Moving (Point a) | |
| update dt p = {p | | |
| x <- p.x + p.vx * dt | |
| , y <- p.y + p.vy * dt | |
| ,vx <- if | mustBounce -(w/2) (w/2) p.x p.vx -> negate p.vx | |
| | otherwise -> p.vx | |
| ,vy <- if | mustBounce -(h/2) (h/2) p.y p.vy -> negate p.vy | |
| | otherwise -> p.vy} | |
| mustBounce : Float -> Float -> Float -> Float -> Bool | |
| mustBounce min max position speed = | |
| (position <= min && speed < 0) || (position >= max && speed > 0) | |
| renderPoint : Point a -> Form | |
| renderPoint {x, y} = | |
| circle 10 |> filled red | |
| |> move (x, y) | |
| render : List Form -> Element | |
| render = collage (round w) (round h) | |
| main : Signal Element | |
| main = render << repeat 1 << renderPoint <~ foldp update {x=0, y=100, vx=0.2, vy=-0.2} (fps 60) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment