Skip to content

Commit

Permalink
Spawn boid at click position
Browse files Browse the repository at this point in the history
  • Loading branch information
MoGrauel committed Jul 28, 2022
1 parent 5fc3383 commit cb78011
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions src/Boid.elm
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ module Boid exposing (main)

import Browser
import Browser.Events
import Html
import Html exposing (Attribute)
import Html.Attributes
import Html.Events
import Html.Events exposing (on)
import Json.Decode
import Svg
import Svg.Attributes

Expand Down Expand Up @@ -45,8 +46,13 @@ type alias V2 =

makeBoid : Boid
makeBoid =
makeBoidV2 { x = 0, y = 0 }


makeBoidV2 : V2 -> Boid
makeBoidV2 pos0 =
Boid
{ pos = { x = 0, y = 0 }
{ pos = pos0
, velocity = { x = 1, y = 1 }
, force = { x = -0.001, y = -0.001 }
}
Expand Down Expand Up @@ -84,7 +90,7 @@ calculateForces bs b =
clampForce : Float -> Boid -> Boid
clampForce limit (Boid boid) =
if vlength boid.force > limit then
clampForce limit (Boid {boid | force = vscale 0.5 boid.force})
clampForce limit (Boid { boid | force = vscale 0.5 boid.force })

else
Boid boid
Expand Down Expand Up @@ -134,26 +140,37 @@ vscale : Float -> V2 -> V2
vscale n v =
{ x = v.x * n, y = v.y * n }


vlength : V2 -> Float
vlength {x, y} = sqrt (x * x + y * y)
vlength { x, y } =
sqrt (x * x + y * y)


onClickWithCoord : (V2 -> Msg) -> Attribute Msg
onClickWithCoord makeMessage =
Json.Decode.map2 (\x y -> Debug.log "msg" <| makeMessage { x = x, y = y })
(Json.Decode.field "offsetX" Json.Decode.float)
(Json.Decode.field "offsetY" Json.Decode.float)
|> on "click"


view : Model -> Html.Html Msg
view model =
Html.div
[ Html.Attributes.style "display" "flex"
, Html.Attributes.style "justify-content" "center"
, Html.Attributes.style "align-items" "center"
, Html.Events.onClick (SpawnBoid makeBoid)
]
[ Svg.svg
[ Svg.Attributes.width (String.fromInt model.world.width)
, Svg.Attributes.height (String.fromInt model.world.height)
, onClickWithCoord (makeBoidV2 >> SpawnBoid)
]
(List.map drawBoid model.boids)
]


drawBoid : Boid -> Svg.Svg msg
drawBoid : Boid -> Svg.Svg Msg
drawBoid (Boid boid) =
Svg.circle
[ Svg.Attributes.cx (String.fromFloat boid.pos.x)
Expand Down

0 comments on commit cb78011

Please sign in to comment.