Hey there,
I'm programming a little game for university reasons. In this game, the player can shoot arrows with a bow, the direction is set by using the arrow keys and you shoot, if space is pressed. The problem is, if I don't put any timed limitations to shooting, you will just shoot infinitely (if keys are hold down for any time you want). Currently I'm using a counter, that increases by one every act. If this counter hit's any number which can be divided by 30, it will allow you to shoot. But this means, if you're unlucky, you would have to hold the spacebar for about a second until an arrow get's shot. Does anyone have any idea, how to fix this, so that you will shoot a new arrow the moment you hit space, but still having a delay between shooting, if the spacebar is hold down?
Current code of my shoot method:
We assume hasBow==true, the counter get's increased by one in the act method.
The top section just takes care about changing images and the player not being able to walk while shooting.
public void shoot(){ if(hasBow==true){ GameWorld world=(GameWorld)getWorld(); int cases=0; if(Greenfoot.isKeyDown("up")||Greenfoot.isKeyDown("right")){ setImage("HoldingBowRight.png"); cases=1; } if(Greenfoot.isKeyDown("down")||Greenfoot.isKeyDown("left")){ setImage("HoldingBowLeft.png"); cases=1; } switch(cases){ case 1: setWalkSpeed(0); break; default: setWalkSpeed(3); break; } if(Greenfoot.isKeyDown("space")&&counter%30==0){ if(Greenfoot.isKeyDown("up")){ world.addObject(new Arrow(270),this.getX(),this.getY()-this.getImage().getHeight()/2); } if(Greenfoot.isKeyDown("right")){ world.addObject(new Arrow(0),this.getX()+this.getImage().getWidth()/2,this.getY()); } if(Greenfoot.isKeyDown("down")){ world.addObject(new Arrow(90),this.getX(),this.getY()+this.getImage().getHeight()/2); } if(Greenfoot.isKeyDown("left")){ world.addObject(new Arrow(180),this.getX()-this.getImage().getWidth()/2,this.getY()); } } } }