Book Image

Creative Greenfoot: RAW

By : Michael Haungs
Book Image

Creative Greenfoot: RAW

By: Michael Haungs

Overview of this book

Table of Contents (17 chapters)
Creative Greenfoot
About the Author
About the Reviewers

Avoider Game with Gamepad

We went over how to connect a gamepad to your Greenfoot scenario and how to use the Gamepad API. Now, it is time to code. We are going to add gamepad support to our version of Avoider Game, which we finished creating in Chapter 2, Animation. You can access a copy of that scenario at

We have two main changes to make to Avoider Game. First, we need to add a reference to a GamePad object associated with our controller and pass that reference between all three worlds in that scenario: AvoiderGameIntroScreen, AvoiderWorld, and AvoiderGameOverWorld. Second, we need to change the Avatar class to be controlled by a gamepad, if present. Otherwise, we default to mouse control.

The entire AvoiderWorld class is not shown in the following code; only the methods that need changing are shown. Here are the changes for AvoiderWorld:

private GamePad pad;

public AvoiderWorld(GamePad p) {
  super(600, 400, 1, false);
  bkgMusic = new GreenfootSound...