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

2014/2/28

Using one key to toggle between two images?

sobia sobia

2014/2/28

#
Hello, I currently have two classes, World and Colors classes. In world class, I basically created Colors object and invoking the method changeColor when space bar press. Clicking on space bar should switch between two imaged color states - blue image and red image. However, when I click the space bar once, it the image changes to blue then red very fast. A better word to describe it is "Lagging". I have to press the space bar multiple of times to toggle between the two colors. The structure must be like this below:
  public class myWorld{
    private boolean isColorChanged = true; // default is blue 
    private Colors colorsObj1 = new Colors();
    private Colors colorsObj2 = new Colors();
    public void act(){      
        if (Greenfoot.isKeyDown("space")){
            if (isColorChanged){
           colorsObj1.setColor(false);   // Change to red with false          
           colorsObj2.setColor(false);
           isColorChanged = false;           
            }else{
           colorsObj1.setColor(true);   // Change to blue with true          
           colorsObj2.setColor(true); 
           isColorChanged = true;          
            }
        }  
    }  
}

public class Colors{

    public void setColor(boolean colorFlag){
      if (colorFlag){
        this.setImage("blue.png");
      }else{
        this.setImage("red.png");
      }

    }

}
Thanks guys!
danpost danpost

2014/2/28

#
You have two options -- and they each work on different changes in state of the "space" key. That is, one executes when the "space" key is initially pressed and the other executes when the "space" key is released. For when released; Change line 6 above to:
if ("space".equals(Greenfoot.getKey()))
For initially pressed:
// add instance field
private boolean spaceDown;
// change line 6 to
if (!spaceDown && Greenfoot.isKeyDown("space")){
    spaceDown = true;
    // etc.
}
// followed by
if (spaceDown && !Greenfoot.isKeyDown("space")){
    spaceDown = false;
}
There is an alternative, you could add a delay between the changing of colors back and forth if the "space" key is held down.
You need to login to post a reply.