From e49d3462d009292fa3c33c5b7eaf1a848ce58b33 Mon Sep 17 00:00:00 2001 From: Alessandro Cattabiani Date: Wed, 29 Nov 2023 18:21:39 +0100 Subject: [PATCH] Cheerp pong tutorial: bound platform movement (#39) Co-authored-by: Alex Bates <16batesa@gmail.com> --- src/content/docs/cheerp/01-tutorials/03-pong.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/content/docs/cheerp/01-tutorials/03-pong.md b/src/content/docs/cheerp/01-tutorials/03-pong.md index a6112e25..85362f31 100644 --- a/src/content/docs/cheerp/01-tutorials/03-pong.md +++ b/src/content/docs/cheerp/01-tutorials/03-pong.md @@ -218,11 +218,11 @@ Let's add two new methods to `Platform`: ```cpp title="pong.cpp" void moveLeft() { - x -= 5; + x = fmax(x-10, 0); } - void moveRight() + void moveRight(int Xmax) { - x += 5; + x += fmin(x+10, Xmax-width); } ``` @@ -235,9 +235,10 @@ void Graphics::keyDownHandler(client::KeyboardEvent* e) if(e->get_keyCode() == 37) platform.moveLeft(); else if(e->get_keyCode() == 39) - platform.moveRight(); + platform.moveRight(400); } ``` +Notice that we are using `fmin` and `fmax` instead of the usual `std::min`/`std::max`. In general, standard library (STL) functions are compiled to Wasm. We can use STL functions from the JS code but there are restrictions. One of these dictates that Wasm functions that have pointers or references to basic types are not available in the JS-annotated part of the code. Indeed, `std::min`/`std::max` get references to basic types while `std::fmin`/`std::fmax` get their inputs by copy. Another solution would have been to wrap `std::min`/`std::max` in non-JS-annotated functions that take `int`s by copy. This limitation will hopefully disappear at some point in the future. Let's also register an `EventListener` in `Graphics::initializeCanvas`.