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

2020/8/8

Increment

Roshan123 Roshan123

2020/8/8

#
if greenfoot.isKeyDown-up then a+=1 here the number is increasing continuously. i want; when the up key is down then a should be 1 and again if the up key is down then the a should be 2 and so on.... What should i write Plz write the code
danpost danpost

2020/8/8

#
Roshan123 wrote...
if greenfoot.isKeyDown-up then a+=1 here the number is increasing continuously. i want; when the up key is down then a should be 1 and again if the up key is down then the a should be 2 and so on.... What should i write Plz write the code
private boolean upKeyDown; // for state of key
private int a;

public void act()
{
    if (upKeyDown != Greenfoot.isKeyDown("up")) // key state changed
    {
        upKeyDown = !upKeyDown;
        if (upKeyDown) a++; // to down state
    }
}
RcCookie RcCookie

2020/8/8

#
You can use this:
//global variable
private boolean pressed = false;

//in act method
if(Greenfoot.isKeyDown("up") && !pressed){
    a++;//does the same as a += 1;
    pressed = true;
}
else{
    pressed = false;
}
I didnt test it but it should work
danpost danpost

2020/8/8

#
RcCookie wrote...
You can use this: << Code Omitted >> I didnt test it but it should work
That will NOT work: When key is pressed: Act # 1: Line 5 is true and pressed is set to true; Act # 2: Line 5 is false and pressed is set back to false; Act # 3: Line 5 is true (again, with key still down) and pressed is set to true; The a is still incremented regularly while the key is held down -- just half as fast.
RcCookie RcCookie

2020/8/8

#
You're right, it has to be like this:
//global variable
private boolean pressed = false;
 
//in act method
if(Greenfoot.isKeyDown("up")){
    if(!pressed){
        a++;
        pressed = true;
    }
}
else{
    pressed = false;
}
danpost danpost

2020/8/8

#
RcCookie wrote...
You're right, it has to be like this: << Code Omitted >>
That is better.
You need to login to post a reply.