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

2014/1/20

Interval at shooting

Tupac Tupac

2014/1/20

#
Hello, this may sound as a very basic question but Im only just starting. I don't want people to shoot at no interval, so how do I set an interval? So for example; if people shoot 2 times, there should be a reloading time. How do I program this in the following?
1
2
3
4
5
6
7
8
if ("space".equals(Greenfoot.getKey()))
{
    fire();
}
if ("space".equals(Greenfoot.getKey()))
{
    XXXX
}
Thanks in advance
kiarocks kiarocks

2014/1/20

#
You'll want a counter that gets set when people fire, so declare a variable, let's call it "FIRE_INTERVAL", in your actor class like so:
1
static final int FIRE_INTERVAL = 100;
'static' means that it will be shared over every actor, and 'final' makes it so it doesn't get changed from what you set it to. Declare another variable called 'fireCountdown':
1
int fireCountdown = 0;
in your actor class, and when someone fires set it to FIRE_INTERVAL:
1
2
fire();
fireCountdown = FIRE_INTERVAL;
Then, put this in the act() method:
1
2
3
if (fireCountdown > 0) {
    fireCountdown--;
}
so the variable goes down. Finally, change
1
("space".equals(Greenfoot.getKey()))
to
1
("space".equals(Greenfoot.getKey()) && fireCountdown == 0)
so that it only lets people fire when fireCountdown is 0. That should do it!
Tupac Tupac

2014/1/26

#
It works, but I can only fire once. So may I ask you: how do I set the interval?
davmac davmac

2014/1/26

#
Don't use Greenfoot.getKey() for this. Use Greenfoot.isKeyDown(...).
Tupac Tupac

2014/1/26

#
davmac wrote...
Don't use Greenfoot.getKey() for this. Use Greenfoot.isKeyDown(...).
This solves the problem, thanks!
You need to login to post a reply.