Example #1
0
  /**
   * Called after the body has moved to update the leg motion accordingly. This method does not use
   * a particularly convincing leg motion algorithm; low-budgets Saturday morning cartoons would be
   * proud.
   */
  public void bodyMovedBy(double dx, double dy) {
    if (anchored) {
      graphics.move(-dx, -dy);
    } else {
      double speed = Math.hypot(dx, dy),
          targetX = restPosition.getX() + dx / speed * rangeOfMotion,
          targetY = restPosition.getY() + dy / speed * rangeOfMotion,
          toTargetX = targetX - graphics.getX(),
          toTargetY = targetY - graphics.getY(),
          distToTarget = Math.hypot(toTargetX, toTargetY);
      graphics.move(toTargetX / distToTarget * speed * 1.5, toTargetY / distToTarget * speed * 1.5);
    }

    double distention =
        Math.hypot(graphics.getX() - restPosition.getX(), graphics.getY() - restPosition.getY());
    if (distention >= rangeOfMotion) anchored = !anchored;
  }
  public void play() {
    GCanvas canvas = getGCanvas();

    ball.move();

    if (ball.getX() < 0 || ball.getX() + ball.getDiameter() > WIDTH) {
      ball.bounceX();
    }

    if (ball.getY() < 0) {
      ball.bounceY();
    }

    if (ball.getY() + ball.getDiameter() > HEIGHT) {
      lives--;
      lifeDisplay.setLabel(String.format("Lives remaining: %d", lives));

      if (lives <= 0) {
        showMessage("DEFEAT!");
      } else {
        ball.setLocation(WIDTH / 2 - BALL_RADIUS, HEIGHT / 2 - BALL_RADIUS);
      }

      return;
    }

    for (int i = 0; i < 4; i++) {
      GPoint point =
          new GPoint(
              ball.getX() + (i & 1) * ball.getDiameter(),
              ball.getY() + ((i & 2) / 2) * ball.getDiameter());
      GObject o = canvas.getElementAt(point);

      if (o == null) {
        continue;
      }

      if (o instanceof BreakoutBrick) {
        canvas.remove(o);
        bricksRemaining--;

        if (bricksRemaining <= 0) {
          showMessage("VICTORY!");
        }
      } else if (o instanceof BreakoutPaddle) {
        paddleBounces++;

        if (paddleBounces > NPADDLE_BOUNCES) {
          paddleBounces = 0;
          ball.accelerate(1.0);
        }
      }

      if (point.getX() < o.getX() + o.getWidth() || point.getX() < o.getX()) {
        ball.bounceX();
      }

      if (point.getY() < o.getY() + o.getHeight() || point.getY() < o.getY()) {
        ball.bounceY();
      }

      return;
    }
  }