Esempio n. 1
0
    public void checkForHit() {

      // change ball speed when ball hits paddle
      if (ball.getShape().intersects(paddle.getShape())) {
        int leftSide = paddle.getX();
        int middleLeft = paddle.getX() + (int) (paddle.getWidth() / 3);
        int middleRight = paddle.getX() + (int) (2 * paddle.getWidth() / 3);
        int rightSide = paddle.getX() + paddle.getWidth();

        if ((ball.getX() >= leftSide) && (ball.getX() < middleLeft)) {
          // change ball speed
          ball.setXspeed(-2);
          ball.setYspeed(-2);
        }
        if ((ball.getX() >= middleLeft) && (ball.getX() <= middleRight)) {
          // change ball speed
          ball.setYspeed(-2);
        }
        if ((ball.getX() > middleRight) && (ball.getX() <= rightSide)) {
          // change ball speed
          ball.setXspeed(2);
          ball.setYspeed(-2);
        }
      }

      // change ball speed when ball hits brick
      for (int i = 0; i < bconfig.getRows(); i++) {
        for (int j = 0; j < bconfig.getCols(); j++) {
          if (bconfig.exists(i, j)) {
            if (ball.getShape().intersects(bconfig.getBrick(i, j).getShape())) {
              Point ballLeft =
                  new Point(
                      (int) ball.getShape().getX(),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight() / 2));
              Point ballRight =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth()),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight() / 2));
              Point ballTop =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth() / 2),
                      (int) ball.getShape().getY());
              Point ballBottom =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth() / 2),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight()));
              if (bconfig.getBrick(i, j).getShape().contains(ballLeft)) {
                // change ball speed
                ball.setXspeed(2);
                score++;
              } else if (bconfig.getBrick(i, j).getShape().contains(ballRight)) {
                // change ball speed
                ball.setXspeed(-2);
                score++;
              }
              if (bconfig.getBrick(i, j).getShape().contains(ballTop)) {
                // change ball speed
                ball.setYspeed(2);
                score++;
              } else if (bconfig.getBrick(i, j).getShape().contains(ballBottom)) {
                // change ball speed
                ball.setYspeed(-2);
                score++;
              }

              // remove brick
              bconfig.removeBrick(i, j);
            }
          }
        }
      }
    }