open SFML.Graphics
open SFML.Window
let window = new RenderWindow(new VideoMode(200u, 200u), "SFML works!")
let shape = new CircleShape(10.0f, FillColor=Color.Green)
let mutable pressedKey = Keyboard.Key.Unknown
let moveKeys = [ Keyboard.Key.Up; Keyboard.Key.Left;
Keyboard.Key.Down; Keyboard.Key.Right ]
let keyPress (e : KeyEventArgs) =
match e.Code with
| moveKeys -> pressedKey <- e.Code
| _ -> pressedKey <- Keyboard.Key.Unknown
let keyRelease (e : KeyEventArgs) =
let pressedKeys = List.filter (fun key -> Keyboard.IsKeyPressed(key)) moveKeys
if pressedKeys.IsEmpty then pressedKey <- Keyboard.Key.Unknown
else pressedKey <- pressedKeys.Head
window.Closed.Add(fun evArgs -> window.Close())
window.KeyPressed.Add(keyPress)
window.KeyReleased.Add(keyRelease)
while window.IsOpen() do
match pressedKey with
| Keyboard.Key.Up -> shape.Position <- new Vector2f(shape.Position.X, shape.Position.Y - 0.1f)
| Keyboard.Key.Left -> shape.Position <- new Vector2f(shape.Position.X - 0.1f, shape.Position.Y)
| Keyboard.Key.Down -> shape.Position <- new Vector2f(shape.Position.X, shape.Position.Y + 0.1f)
| Keyboard.Key.Right -> shape.Position <- new Vector2f(shape.Position.X + 0.1f, shape.Position.Y)
| _ -> ()
window.DispatchEvents()
window.Clear()
window.Draw(shape)
window.Display()
In the above code example, I create a circle and let it move by pressing the arrow keys. The state variable represents the position of the circle represented by the Vector2f object (part of the SFML library)
My question relates to the end of the code segment, where I find the key pressed, and then move the circle. From C # background, this part of my code seems bad.
In C #, I would just do the following:
switch (pressedKey) {
case Keyboard.Key.Up:
shape.Position.Y -= 0.1f;
}
source
share