I\'m trying to create custom keyboard controls for a 4 player game. Right now, the keys are predetermined like this:
type Orient = { x:Int, y:Int }
type Gam
Directly using Keyboard.directions
is not gonna work. The problem is that at the start of the game the keys can be changed so you have some Signal Char
. And Keyboard.direction
goes from "normal types" to "signal types". So you can't lift it.
But you also have access to the keys that are currently held down, Keyboard.keysDown
. I looked up the implementation of Keyboard.directions and I think you can recreate it in Elm in a way that has it take Signal Int
arguments.
Here's an Elm implementation of the normal Keyboard.directions
:
directions : Int -> Int -> Int -> Int -> Signal { x : Int, y : Int }
directions up down left right =
(\kd ->
List.filter (\ky -> List.member ky [up,down,left,right]) kd |>
List.foldl (\ky st -> if | ky == up -> { st | y <- st.y + 1 }
| ky == down -> { st | y <- st.y - 1 }
| ky == left -> { st | x <- st.x - 1 }
| ky == right -> { st | x <- st.x + 1 }
) {x=0,y=0}
) <~ Keyboard.keysDown
and here's the implementation you'll want to use:
directions : Signal Int -> Signal Int -> Signal Int -> Signal Int -> Signal { x : Int, y : Int }
directions up down left right =
(\u d l r kd ->
List.filter (\ky -> List.member ky [u,d,l,r]) kd |>
List.foldl (\ky st -> if | ky == u -> { st | y <- st.y + 1 }
| ky == d -> { st | y <- st.y - 1 }
| ky == l -> { st | x <- st.x - 1 }
| ky == r -> { st | x <- st.x + 1 }
) {x=0,y=0}
) <~ up ~ down ~ left ~ right ~ Keyboard.keysDown
Feel free to refactor, I just hacked this code together quickly so it's kind of too large for a single function.