Skip to content

Commit

Permalink
Add turning
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Oct 22, 2021
1 parent a409086 commit 5db31c9
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 10 deletions.
10 changes: 10 additions & 0 deletions ZATACKA.html
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ <h1>Achtung, die Kurve!</h1>
app.ports.myPort.subscribe(model => {
renderer.drawSquare(model.x, model.y, 3, "red")
})


document.addEventListener("keydown", event => {
event.preventDefault()
app.ports.onKeydown.send(event.key)
})
document.addEventListener("keyup", () => {
// Traditionally we never prevented default on keyup.
app.ports.onKeyup.send(event.key)
})
</script>

</body>
Expand Down
69 changes: 59 additions & 10 deletions src/Main.elm
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
port module Main exposing (main)

import Browser.Events exposing (onKeyDown)
import Platform exposing (worker)
import Set exposing (Set)
import Time


port myPort : Model -> Cmd msg
port myPort : { x : Float, y : Float } -> Cmd msg


port onKeydown : (String -> msg) -> Sub msg


port onKeyup : (String -> msg) -> Sub msg


tickrate : Float
Expand All @@ -13,37 +21,78 @@ tickrate =


type alias Model =
{ x : Int
, y : Int
{ x : Float
, y : Float
, direction : Float
, pressedKeys : Set String
}


init : () -> ( Model, Cmd Msg )
init _ =
( { x = 0, y = 0 }, Cmd.none )
( { x = 0
, y = 0
, direction = 0.5
, pressedKeys = Set.empty
}
, Cmd.none
)


type Msg
= Msg Int
= Tick Time.Posix
| KeyWasPressed String
| KeyWasReleased String


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Msg _ ->
Tick _ ->
let
theta =
1

angleChange =
0.1

newDirection =
if Set.member "m" model.pressedKeys then
model.direction + angleChange

else if Set.member "," model.pressedKeys then
model.direction - angleChange

else
model.direction

newModel =
{ model
| x = model.x + 1
, y = model.y + 2
| x = model.x + theta * cos newDirection
, y = model.y + theta * sin newDirection
, direction = newDirection
}
in
( newModel, myPort newModel )
( newModel, myPort { x = newModel.x, y = newModel.y } )

KeyWasPressed key ->
( { model | pressedKeys = Set.insert key model.pressedKeys }
, Cmd.none
)

KeyWasReleased key ->
( { model | pressedKeys = Set.remove key model.pressedKeys }
, Cmd.none
)


subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every (1000 / tickrate) (Time.posixToMillis >> Msg)
Sub.batch
[ Time.every (1000 / tickrate) Tick
, onKeydown KeyWasPressed
, onKeyup KeyWasReleased
]


main =
Expand Down

0 comments on commit 5db31c9

Please sign in to comment.