Gameboy Programming: Using the Joypad

In the last tutorial I showed how to create a sprite, and animate it. in this lesson, I will demonstrate how to use the gamepad to move your characters and start to build some interactivity to your games.

The good news is that we don’t have to change much of the previously written code in able to implement our basic control scheme.

The Code

The top part of our code doesn’t change –

Once we reach the While Loop however you will notice some additions

You should notice a call to the joypad function. This checks which key has been pressed on the Gameboy’s joypad. In order to give specific instructions to the gameboy when each keypress is detected we wrap these in a Switch statement. A switch statement is a more concise version of an if / else statement .

Here we feed in the different cases for the outcomes of the player pressing a button on the joypad. If left is pressed (this is the keyword J_LEFT) then we move the sprite 10 pixels to the left. This is using the keyword scroll_sprite which tells the gameboy development kit to move the sprite in a particular direction.

On the gameboy screen negative numbers horizontally mean left, positive numbers mean right, on the vertical axis, negative numbers are up and positive numbers are down.

We then set a delay so that the sprite isn’t zipping off the screen, this checks the joypad input every 100 cycles.

When you build the file and run it on the emulator you should get:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s