This site requires JavaScript, please enable it in your browser!
Greenfoot back
murphys
murphys wrote ...

2012/2/16

Keypress issue

murphys murphys

2012/2/16

#
I have reused some code so that a keypress will add an object to the screen. The code has the test isDown to check that the key has been depressed before extra objects are added. This works as expected when placed in a subclass of World. However, it doesn't work when placed into the subclass of Actor that the object is an instance of. Multiple copies are added (at a seemingly exponential rate) even though the key hasn't been depressed. Can someone explain why the same code produces different results please? public void openNote() { if (!isDown && Greenfoot.isKeyDown("down")) { addObject(new Note(), Greenfoot.getRandomNumber(400), Greenfoot.getRandomNumber(400)); isDown = true; } if (!Greenfoot.isKeyDown("down")) { isDown = false; } } The boolean isDown was decalared in both attempts. Many thanks, Steven.
Morran Morran

2012/2/16

#
I'll go ahead and try to figure out what's wrong with your code, but in the mean time, why don't you just use Greenfoot.getKey()? Like:
public void openNote() { 
  String key = Greenfoot.getKey();
  if(key != null) {
   if (key.equals("down")) { 
   addObject(new Note(), Greenfoot.getRandomNumber(400),  Greenfoot.getRandomNumber(400)); 
   }
  }
}
nccb nccb

2012/2/16

#
That code doesn't look like it can add a new note unless the "down" key is down. However, if that code is called from the act method of Note, and the isDown variable is non-static (i.e. it is a standard field), then when you do press "down", every instance of the Note actor will add a new Note, because each is keeping track of the key's state independently. And because each Note adds a new Note, you'll get a doubling of the number of notes in each frame in which "down" is pressed. The solution would be either to move it back to the world, or to make the field static:
private static boolean isDown;
Static means it's shared among all the Notes, and thus only one each act() cycle can add a new Note.
Morran Morran

2012/2/16

#
@nccb that makes lots of sense.
You need to login to post a reply.