簡體   English   中英

Java 圖形 drawOval() 兩個橢圓之間的交集

[英]Java Graphics drawOval() intersection between two ovals

我想實現一個碰撞檢測機制來檢測兩個橢圓之間的碰撞。 我正在使用 Java 圖形繪制橢圓,我想檢查它們是否重疊。 有沒有辦法做到這一點?

樣品橢圓:

drawOval(x, y, 24, 24);
drawOval(x, y, 100, 142);

drawOval(x,y,width,height) - Java 圖形 function x - 要繪制的橢圓左上角的 x 坐標。 y - 要繪制的橢圓左上角的 y 坐標。 width - 要繪制的橢圓的寬度。 height - 要繪制的橢圓的高度。

僅繪制橢圓對您沒有幫助,相反,您需要使用更重要的 object,更多的內部數據和行為將允許您執行這些查詢。 幸運的是,Graphcs2D 庫中存在這種類型的 object: Shape 接口及其子類型,此處為 Ellipse2D。 創建一個Ellipse2D object 然后您可以使用Graphics2D g2d.draw(myEllipse)繪制它並使用.intersects(...)方法檢查相交。

例如,

// declare and initialize fields
private int x = 0;
private int y = 0;
private Ellipse2D myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
private Ellipse2D myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);
// draw your shapes in the drawing JPanel
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    // change the g2d's color?
    g2d.draw(myEllipse1);

    // change the g2d's color?
    g2d.draw(myEllipse2);

    // ...
}

其他地方,例如在 Swing 計時器的 ActionListener 中:

// set location values to proper value
x = somethingNew;
y = somethingElseNew;

// create new Ellipse2D objects based on the x,y changes
myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);

// test for intersection
if (myEllipse1.intersects(myEllipse2) {
    // do something
}

// ask the GUI to re-draw itself
repaint();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM