如何在java中使图形对象固定?

时间:2013-10-22 20:01:07

标签: java collision-detection game-physics

我正在制作一个简单的游戏,我需要这些只是闲置的方块,当被击中时,碰撞并反射球。但目前球只是飞过我的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);
  }
}

2 个答案:

答案 0 :(得分:3)

您需要检测球何时与保险杠发生碰撞。你有BouncingBall的boundingBox()方法,这会得到一个包含你的球的矩形。因此,您需要检查此矩形是否与方形保险杠相交(这意味着碰撞),然后对其执行某些操作。

答案 1 :(得分:3)

查看实现Shape接口的类。有椭圆和其他形状,它们都实现了intersects(Rectangle2D)方法。如果您不想自己进行交叉,这可能对您有所帮助。

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