Home > Computer Programming > Problems using getKey() in Greenfoot

Problems using getKey() in Greenfoot

November 26, 2012 Leave a comment Go to comments

If you have two actors checking what the last key pressed was, you might run into a problem. The problem occurs because when Player 1 checks the key, he sets it to null. That means when Player 2 checks the key, it isn’t there any more. Imagine if Player 1 fires when you press “q” and Player 2 fires if you press “p”. You run the game and press “p”. Player 2 should fire but he doesn’t. What’s happened is that Player 1 made a call to getKey() first and in doing so reset the key to null. Then Player 2 made his call to getKey() and it returned null. You can check this is true by adding Player 2 to the world before Player 1. Now you will find that it’s Player 1 whose fire button doesn’t work and Player 2’s does.

The solution is to implement an act() method in your world class. Here you make your one single call to getKey() and you store the result in a static variable. Once this is done your actors can poll the value of this static variable and react to it without making their own calls to getKey().

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s