0
\$\begingroup\$

U'm currently trying to develop a 2D RPG similar to early Final Fantasy titles for the NES.

Up until now I've been reading C++ tutorials on SDL2 and doing my best to convert the concepts into OCaml. However, I'm not sure how I should handle input.

Right now I'm just reading keyboard input in my main game loop as such:

let handle_events game =
  let e = Sdl.Event.create () in
  let _ = Sdl.poll_event (Some e) in
  match Sdl.Event.(enum (get e typ)) with
  | `Quit -> game.running <- false
  | `Key_down -> print_endline "key was pressed"
  | _ -> ()

(For those unfamiliar with functional pattern matching, a match statement here kind of behaves like a switch-case statement) This janky "event handler" is then called every frame in my main, as such:

  while game.running do
    frame_start := Int32.to_int (Sdl.get_ticks ());
    Game_loop.handle_events game;
    Game_loop.update game;
    Game_loop.render game;
    frame_time := Int32.to_int (Sdl.get_ticks ()) - !frame_start;
    if frame_delay > !frame_time then
      Sdl.delay (Int32.of_int (frame_delay - !frame_time))
  done;

The problem is, this approach does not seem to be well-performing — sometimes when I press a key repeatedly or hold a key down, the game takes seconds before "key was pressed" shows up in the console. That, and sometimes I can't even quit the game.

I'm have a feeling I'm going about this the wrong way, but how?

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

@DMGregory found the issue regarding the lag — it was the fact that my event handler was only handling one event per frame. Changing it to a while loop over Sdl.poll_event fixed the lag.

let handle_events game =
  let e = Sdl.Event.create () in
  while Sdl.poll_event (Some e) do
    match Sdl.Event.(enum (get e typ)) with
    | `Quit -> game.running <- false
    | `Key_down -> (
        match
          Sdl.Event.get e Sdl.Event.keyboard_keycode |> Sdl.get_key_name
        with
        | "W" -> Sprite.update game.player_ecs 0 (-10)
        | _ -> ())
    | _ -> ()
  done
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .