Say we wanted to create a browser-based version of the classic arcade game Asteroids, where the mouse position controlled the movement of the game’s spaceship and the blaster was triggered by pressing the spacebar. How would we go about programming those actions?
The p5.js library makes it easy to add interactivity to do something like that! It provides tools that let us turn mouse and keyboard inputs into creative interactions within the canvas!
In this lesson, we will look at the various kinds of interaction that are foundational to p5.js. Specifically, we will look at how to combine key and mouse events to trigger events and move drawn shapes around, creating more versatile programs.
Take a look at the browser window to the right. There is a basic version of the Asteroids arcade game. When we move our mouse around the p5.js canvas, we can see that the ship follows the mouse movement. Press the spacebar to trigger the blaster. Lastly, try holding the mouse down while we fire the blaster.
Explore the sketch, and when you’re ready, click “Next” to get started with learning about mouse interactions!