|
1 | | -#include <stddef.h> |
2 | 1 | #include <emscripten/emscripten.h> |
3 | 2 |
|
4 | | -static const char GREETING[] = "Hello from WebAssembly!"; |
| 3 | +static float canvas_width = 640.0f; |
| 4 | +static float canvas_height = 480.0f; |
| 5 | +static float ball_x = 320.0f; |
| 6 | +static float ball_y = 240.0f; |
| 7 | +static float ball_radius = 16.0f; |
| 8 | +static float velocity_x = 180.0f; |
| 9 | +static float velocity_y = 140.0f; |
| 10 | + |
| 11 | +static void clamp_ball_inside_canvas(void) |
| 12 | +{ |
| 13 | + if (ball_x < ball_radius) { |
| 14 | + ball_x = ball_radius; |
| 15 | + } else if (ball_x > canvas_width - ball_radius) { |
| 16 | + ball_x = canvas_width - ball_radius; |
| 17 | + } |
| 18 | + |
| 19 | + if (ball_y < ball_radius) { |
| 20 | + ball_y = ball_radius; |
| 21 | + } else if (ball_y > canvas_height - ball_radius) { |
| 22 | + ball_y = canvas_height - ball_radius; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +EMSCRIPTEN_KEEPALIVE |
| 27 | +void set_canvas_size(int width, int height) |
| 28 | +{ |
| 29 | + if (width > 0) { |
| 30 | + canvas_width = (float)width; |
| 31 | + } |
| 32 | + |
| 33 | + if (height > 0) { |
| 34 | + canvas_height = (float)height; |
| 35 | + } |
| 36 | + |
| 37 | + clamp_ball_inside_canvas(); |
| 38 | +} |
| 39 | + |
| 40 | +EMSCRIPTEN_KEEPALIVE |
| 41 | +void reset_ball(void) |
| 42 | +{ |
| 43 | + ball_x = canvas_width * 0.5f; |
| 44 | + ball_y = canvas_height * 0.5f; |
| 45 | + velocity_x = 180.0f; |
| 46 | + velocity_y = 140.0f; |
| 47 | + clamp_ball_inside_canvas(); |
| 48 | +} |
| 49 | + |
| 50 | +EMSCRIPTEN_KEEPALIVE |
| 51 | +void update(float delta_seconds) |
| 52 | +{ |
| 53 | + if (delta_seconds <= 0.0f) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + ball_x += velocity_x * delta_seconds; |
| 58 | + ball_y += velocity_y * delta_seconds; |
| 59 | + |
| 60 | + if (ball_x - ball_radius < 0.0f) { |
| 61 | + ball_x = ball_radius; |
| 62 | + velocity_x = -velocity_x; |
| 63 | + } else if (ball_x + ball_radius > canvas_width) { |
| 64 | + ball_x = canvas_width - ball_radius; |
| 65 | + velocity_x = -velocity_x; |
| 66 | + } |
| 67 | + |
| 68 | + if (ball_y - ball_radius < 0.0f) { |
| 69 | + ball_y = ball_radius; |
| 70 | + velocity_y = -velocity_y; |
| 71 | + } else if (ball_y + ball_radius > canvas_height) { |
| 72 | + ball_y = canvas_height - ball_radius; |
| 73 | + velocity_y = -velocity_y; |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +EMSCRIPTEN_KEEPALIVE |
| 78 | +float get_ball_x(void) |
| 79 | +{ |
| 80 | + return ball_x; |
| 81 | +} |
5 | 82 |
|
6 | 83 | EMSCRIPTEN_KEEPALIVE |
7 | | -const char *get_greeting(void) |
| 84 | +float get_ball_y(void) |
8 | 85 | { |
9 | | - return GREETING; |
| 86 | + return ball_y; |
10 | 87 | } |
11 | 88 |
|
12 | 89 | EMSCRIPTEN_KEEPALIVE |
13 | | -size_t get_greeting_length(void) |
| 90 | +float get_ball_radius(void) |
14 | 91 | { |
15 | | - return sizeof(GREETING) - 1; |
| 92 | + return ball_radius; |
16 | 93 | } |
0 commit comments