fix rendering, fix the way we use request_animation_frame

This commit is contained in:
zapashcanon 2022-12-08 02:09:23 +01:00
parent 1b89d35dfd
commit b89202dfb0
Signed by untrusted user who does not match committer: zapashcanon
GPG Key ID: 8981C3C62D1D28F1

View File

@ -1,3 +1,13 @@
open Brr
open Brr_canvas
module G = struct
include Brr.G
let request_animation_frame f =
(ignore : int -> unit) @@ Brr.G.request_animation_frame f
end
let () = Random.self_init ()
module Map = struct
@ -20,9 +30,6 @@ module Map = struct
let get_tile_kind ~x ~y = try m.(x).(y) with Invalid_argument _ -> Black
end
open Brr
open Brr_canvas
let get_el id =
match Document.find_el_by_id G.document (Jstr.of_string id) with
| None -> failwith (Format.sprintf {|Could not find element by id: "%s"|} id)
@ -30,9 +37,9 @@ let get_el id =
let tile_size = 40
let width = 835
let width = 875
let height = 635
let height = 675
let canvas =
let el = get_el "canvas" in
@ -40,7 +47,7 @@ let canvas =
let context = C2d.get_context canvas
let init_bg () =
let init () =
Canvas.set_w canvas width;
Canvas.set_h canvas height;
C2d.set_fill_style context (C2d.color (Jstr.v "#FF1188"));
@ -80,8 +87,8 @@ let draw_map _timestamp =
done
done;
C2d.draw_image context papy_bottom
~x:(float_of_int (width / 2))
~y:(float_of_int (height / 2))
~x:(float_of_int (width - tile_size) /. 2.)
~y:((float_of_int height /. 2.) -. float_of_int tile_size)
let kb_handler ev =
let x, y = !Map.player_pos in
@ -97,26 +104,29 @@ let kb_handler ev =
let x = min (Map.width - 1) x in
let y = max 0 y in
let y = min (Map.height - 1) y in
Map.player_pos := (x, y);
let _animation_frame_id = G.request_animation_frame draw_map in
()
Map.player_pos := (x, y)
let rec game_loop _timestamp =
(* ... update state ... *)
let rec game_loop state _timestamp =
draw_map ();
ignore @@ G.request_animation_frame game_loop
let new_state = state in
G.request_animation_frame (game_loop new_state)
let on_window_load f x =
(ignore : Ev.listener -> unit)
@@ Ev.listen Ev.load
(fun (_ev : Ev.Type.void Ev.t) -> f x)
(Window.as_target G.window)
let bind_keys () =
(ignore : Ev.listener -> unit)
@@ Ev.listen Ev.keydown kb_handler (Window.as_target G.window)
(* type will change later !*)
let initial_state = ()
let () =
let on_window_load f x =
ignore
@@ Ev.listen Ev.load (fun _ev -> ignore @@ f x) (Window.as_target G.window)
in
let bind_keys () =
ignore
@@ Ev.listen Ev.keydown
(fun ev -> kb_handler ev)
(Window.as_target G.window)
in
on_window_load init_bg ();
on_window_load init ();
on_window_load bind_keys ();
on_window_load G.request_animation_frame game_loop
on_window_load
(fun () -> G.request_animation_frame (game_loop initial_state))
()