1
\$\begingroup\$

I was wondering how to cause the bullets to delay since at the moment, they fire pretty much one after another. So I was wondering how to make each bullet be delayed by one second when the space bar is pressed/held down.

public class TheGun extends GunType{

  private Rectangle bullet;
  private final double speed = 3d;

  public TheGun(double xPos, double yPos, int width,int height){
    this.setxPos(xPos);
    this.setyPos(yPos);
    this.setWidth(width);
    this.setHeight(height);

    this.bullet = new Rectangle((int) getxPos(),(int) getyPos(), getWidth(), getHeight());
  }

  @Override
  public void draw(Graphics2D g) {
    if(bullet == null)
      return;

    g.setColor(Color.YELLOW);
    g.fill(bullet);
  }

  @Override
  public void update(double delta, BlockyBlocks blocks) {
    if(bullet == null)
      return;

    this.setyPos(getyPos() - (delta * speed - 1));
    bullet.y = (int) this.getyPos();
    wallCollide(blocks);
    isOutofBounds();
  }

  @Override
  public boolean collisionRect(Rectangle rect) {
    if(this.bullet == null)
      return false;

    if(bullet.intersects(rect)){
      this.bullet = null;
      return true;
    }

    return false;
  }

  @Override
  public boolean collisionPoly(Polygon poly) {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public boolean destroy() {
    if(bullet == null)
      return true;

    return false;
  }

  @Override
  protected void wallCollide(BlockyBlocks blocks) {
    for(int i = 0; i < blocks.wall.size(); i++){
      if(bullet.intersects(blocks.wall.get(i))){
        blocks.wall.remove(i);
        bullet = null;
        return;
      }
    }
  }

  @Override
  protected void isOutofBounds() {
    if(this.bullet == null)
      return;

    if(bullet.y < 0 || bullet.y > Sea_InvadersDisplay.HEIGHT || bullet.x < 0 || bullet.x > Sea_InvadersDisplay.WIDTH){
      bullet = null;
    }
  }
}
\$\endgroup\$
  • \$\begingroup\$ You should really stick to a single naming style when programming. \$\endgroup\$ – Bálint Jan 27 '17 at 11:57
  • \$\begingroup\$ In the future, you can use the "Code sample" button from the edit toolbar to format your code. \$\endgroup\$ – Vaillancourt Jan 27 '17 at 11:59
2
\$\begingroup\$

What you can simply do is keeping the last bullet launched time, and when trying to fire check if the ellapsed time is over 1 second to launch the next bullet.

It could look like this

uint timeLastBullet = 0; // Initialize before game loop

if (spacePressed) // In game loop
{
    if (GetTime() - timeLastBullet >= 1000) //If GetTime returns milliseconds
    {
        Fire();
        timeLastBullet = GetTime();
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.