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

2013/2/18

Counter counts down by one when tool is used.

kaciedy kaciedy

2013/2/18

#
I am working on the scenario Asteroids and what my objective is presently is to create a counter separate from the points counter which I have running smoothly to count down from 5 and once the counter is 0 proton wave can no longer be used. Each time it runs however, when I press control, it counts down once from 5 to -5 and it counts down for as long at control is pressed. Here is what I have that is connected to this.
Rocket Class
private int down = 5;

private void checkKeys() 
    {
     
        if(Greenfoot.isKeyDown("control") && down <= 5)
        {
            startProtonWave();
            down--;
            space.minusWave(); 
        }
}
public class pCounter extends Actor
{
    private static final Color textColor = new Color(255, 180, 150);
    
    private int value = 0;
    public int target = 5;
    private String text;
    private int stringLength;
    
    /**
     * 
     */
    public pCounter()
    {
        this("");
    }

    /**
     * 
     */
    public pCounter(String prefix)
    {
        text = prefix;
        stringLength = (text.length() + 2) * 10;
        setImage(new GreenfootImage(stringLength, 16));
        GreenfootImage image = getImage();
        image.setColor(textColor);

        updateImage();

    }
    
  
    /**
     * 
     */
    public void act()
    {
        if(value < target) 
        {
            value++;
            updateImage();
        }
        else if(value > target)
        {
            value--;
            updateImage();
        }
    }
    
    /**
     * 
     */
    public void add(int score)
    {
        target += score;
    }

    /**
     * 
     */
    public int getValue()
    {
        return value;
    }

    /**
     * Make the image
     */
    private void updateImage()
    {
        GreenfootImage image = getImage();
        image.clear();
        image.drawString(text + value, 1, 12);
    }
}
Space Class
    public void minusWave()
    {
        pWave.add(-1);
    }
danpost danpost

2013/2/18

#
You need to track the state of the control key by adding an instance boolean field (I will call it controlDown).
private int down = 5;
private boolean controlDown;

private void checkKeys() 
{
    if (down != 0 && !controlDown && Greenfoot.isKeyDown("control"))
    {
        startProtonWave();
        down--;
        controlDown=true;
        space.minusWave(); 
    }
    if (controlDown && !Greenfoot.isKeyDown("control"))
    { // check for control key release
        controlDown=false;
    }
}
You need to login to post a reply.