0

我正在开发一个简单的游戏,我需要这些 squareBumpers,它们只是闲置,当被击中时,碰撞并反射球。但目前球只是飞过我的 squareBumpers。我只能使用 java awt 和 swing 库。这是代码:

class squareBumper {
      private int x = 300;
      private int y = 300;
      private Color color = new Color(66,139,139);

      public void paint(Graphics g) {
        Rectangle clipRect = g.getClipBounds();
          g.setColor(color);
          g.fillRect(x, y, 31, 31);
      }
   }

class BouncingBall {
  // Overview: A BouncingBall is a mutable data type.  It simulates a
  // rubber ball bouncing inside a two dimensional box.  It also
  // provides methods that are useful for creating animations of the
  // ball as it moves.

  private int x = 320;
  private int y = 598;
  public static double vx;
  public static double vy; 
  private int radius = 6;
  private Color color = new Color(0, 0, 0);

  public void move() {
    // modifies: this
    // effects: Move the ball according to its velocity.  Reflections off
    // walls cause the ball to change direction.
    x += vx;
    if (x <= radius) { x = radius; vx = -vx; }
    if (x >= 610-radius) { x = 610-radius; vx = -vx; }

    y += vy;
    if (y <= radius) { y = radius; vy = -vy; }
    if (y >= 605-radius) { y = 605-radius; vy = -vy; }
  }

  public void randomBump() {
    // modifies: this
    // effects: Changes the velocity of the ball by a random amount
    vx += (int)((Math.random() * 10.0) - 5.0);
    vx = -vx;
    vy += (int)((Math.random() * 10.0) - 5.0);
    vy = -vy;
  }

  public void paint(Graphics g) {
    // modifies: the Graphics object <g>.
    // effects: paints a circle on <g> reflecting the current position
    // of the ball.

    // the "clip rectangle" is the area of the screen that needs to be
    // modified
    Rectangle clipRect = g.getClipBounds();

    // For this tiny program, testing whether we need to redraw is
    // kind of silly.  But when there are lots of objects all over the
    // screen this is a very important performance optimization
    if (clipRect.intersects(this.boundingBox())) {
      g.setColor(color);
      g.fillOval(x-radius, y-radius, radius+radius, radius+radius);
    }
  }

  public Rectangle boundingBox() {
    // effect: Returns the smallest rectangle that completely covers the
    //         current position of the ball.

    // a Rectangle is the x,y for the upper left corner and then the
    // width and height
    return new Rectangle(x-radius, y-radius, radius+radius+1, radius+radius+1);
  }
}
4

2 回答 2

3

看看实现Shape接口的类。有椭圆等形状,都实现了一个intersects(Rectangle2D)方法。如果您不想自己执行交集,它可能会对您有所帮助。

至于处理碰撞,这取决于你想要的准确度。简单地偏转边缘球非常容易。只需判断矩形的碰撞边是垂直的还是水平的,并相应地取反相应的速度分量。如果你想处理角落,那就有点复杂了。

于 2013-10-22T20:10:18.543 回答
3

您需要检测球何时与保险杠发生碰撞。你有 BouncingBall 的 boundingBox() 方法,这会给你一个包含你的球的矩形。所以你需要检查这个矩形是否与你的方形保险杠相交(这意味着碰撞),然后用它做一些事情。

于 2013-10-22T20:04:57.703 回答