2013-10-22 46 views
0

我正在做一個簡單的遊戲,我需要這些squareBumpers,它們只是閒置,當碰撞,碰撞和反射球。但目前球只是通過我的方形籃球飛行。我只能使用java awt和swing庫。代碼如下:我該如何在java中製作一個圖形對象?

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); 
    } 
} 
+0

你的速度分量是「靜態」嗎? – Zong

+0

是的,我從不同類中收到的xml模式獲取速度值。 – Umut

+0

'靜態'不應該與值的來源有關。它將變量的語義從實例成員更改爲類成員。這意味着你所有的BouncingBall將始終具有相同的速度。 – Zong

回答

3

查看實現Shape接口的類。有橢圓形和其他形狀,它們都實現了intersects(Rectangle2D)方法。它可以幫助你,如果你不想自己執行交集。

至於處理碰撞,那麼它取決於你想要的精度水平。簡單地偏轉球的邊緣很容易。只需確定矩形的碰撞邊是垂直還是水平,並相應地否定相應的速度分量。如果你想要處理角落,那麼這有點複雜。

3

您需要檢測球何時與保險槓碰撞。你有BouncingBall的boundingBox()方法,這會得到一個包含你的球的矩形。所以你需要檢查這個矩形是否與你的方形保險槓相交(這意味着碰撞),然後用這個做一些事情。

相關問題