Keyboard Input

Now that we have sprites and animations, and can move these sprites around our canvas, we will need to add some interaction into our game. There are a few ways we can get keyboard input for our game. One way is through JavaScript, making calls to different functions in our WebAssembly module based on that input. The first section of our code will do just that. We will add some functions inside the WebAssembly module for us to wrap in JavaScript wrappers. We will also set up some JavaScript keyboard event handlers that we will use to make calls into our WebAssembly module whenever the keyboard events are triggered.

The other way we can get input into our WebAssembly module is to allow SDL to do all the heavy lifting for us. That involves adding C code into our WebAssembly module that captures the SDL_KEYDOWN and SDL_KEYUP events. The module will then look at the event keycode to determine what key triggered the event. There are costs and benefits to writing our code using either method. Generally speaking, having SDL managing our keyboard input costs us some of the flexibility of writing our keyboard input manager inside the JavaScript, while, at the same time, we gain the benefit of more straightforward code.

You will need to include several images in your build to make this project work. Make sure you include the /Chapter05/sprites/ folder from the project's GitHub. If you haven't yet downloaded the GitHub project, you can get it online at:  https://github.com/PacktPublishing/Hands-On-Game-Development-with-WebAssembly.

In this chapter, we will do the following:

  • Learn how to use JavaScript keyboard events to make calls into our WebAssembly module
  • Learn how to use SDL events to manage keyboard input from inside our WebAssembly module
  • Demonstrate what we have learned by using keyboard input to move a spaceship sprite around the canvas