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

2022/8/2

How can I put a delay between bullets?

DavidZyy DavidZyy

2022/8/2

#
Hello! I am quite new to java and greenfoot and were tasked with adding a delay between bullets on a spaceship project. This is the spaceship code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Spaceship here. * * @author (your name) * @version (a version number or a date) */ public class Spaceship extends Actor { int speed = 5; /** * Act - do whatever the Spaceship wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. move(); shoot(); } public void move() { if (Greenfoot.isKeyDown("a")) setLocation(getX()-speed,getY()); if (Greenfoot.isKeyDown("d")) setLocation(getX()+speed,getY()); if (Greenfoot.isKeyDown("w")) setLocation(getX(),getY()-speed); if (Greenfoot.isKeyDown("s")) setLocation(getX(),getY()+speed); } public void shoot(){ if (Greenfoot.isKeyDown("space")){ Bullet bullet = new Bullet(); World world = getWorld(); world.addObject(bullet, getX(), getY()); } } } And this is the bullet code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Bullet here. * * @author (your name) * @version (a version number or a date) */ public class Bullet extends Actor { int speed = 7; public Bullet() { setRotation(-90); } public void act() { // Add your action code here. move(speed); } }
Spock47 Spock47

2022/8/2

#
First thing is to decide how long the delay between two bullets should be, e.g. "2 seconds". Since Greenfoot regularly calls the act method, the unit for the delay should be "number of calls to the act method" (/"cycles"). On normal speed, Greenfoot calls the act method approximately 60 times a second. 1. So, let's define a constant for the duration until the next bullet can be fired:
    private static int COOLDOWN_MAX = 120; // 60 for each second. 
2. Next, an attribute is needed that stores the current state of the cooldown, e.g. storing the remaining time (in cycles) until the cannon can fire again:
    private int cannonCooldown = 0;
3. Then, after fireing a bullet, the cooldown has to be started (set to max value):
        cannonCooldown = COOLDOWN_MAX;
4. + 5. Finally, the cooldown has to be counted down and a check is needed that ensures that a bullet can only be started when the cooldown is completed:
        if (cannonCooldown > 0) {
            cannonCooldown--;
        } else if (Greenfoot.isKeyDown("space")) {
Live long and prosper, Spock47
You need to login to post a reply.