2012-08-26 109 views
-1

有很多像這樣的問題,但我檢查了所有問題,但都沒有解決我遇到的問題,因此請不要將它作爲重複項來關閉。在java中使用圓圈進行碰撞檢測

我正在製作一箇中間有一個大圓圈的遊戲,周圍是六個其他圈子,這些圈子的大小逐漸增加。如果六圈中的一圈與中央圈發生碰撞,我想結束比賽。任何人都能提供合適的解決方案

這裏是我的代碼:

package virus; 


import java.awt.*; 
import java.util.Random; 
import javax.swing.JPanel; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 


public class VirusGamePanel extends JPanel implements MouseListener{ 
    private static final long serialVersionUID = 1L;//serialVersionUID field 
    Random colour = new Random();//the outside ovals will always be a random colour 
    private int sizeX1 = 0;//the x size of the outside ovals 
    private int sizeX2 = 0; 
    private int sizeX3 = 0; 
    private int sizeX4 = 0; 
    private int sizeX5 = 0; 
    private int sizeX6 = 0; 

    private int sizeY1 = 0;//the y size of the outside ovals 
    private int sizeY2 = 0; 
    private int sizeY3 = 0; 
    private int sizeY4 = 0; 
    private int sizeY5 = 0; 
    private int sizeY6 = 0; 
    int score = 0; 

    static String scorestring = "Score: "; 
    Color rand = new Color(colour.nextInt(255), colour.nextInt(255), colour.nextInt(255)); //generate the random colour 

    public void paint(Graphics g) 
    { 
     super.paint(g); 
     g.setColor(Color.magenta); 
     g.drawString(scorestring+score,275,250); 
     g.setColor(Color.orange); 
     g.drawOval(200, 150, 200, 200); 
     g.setColor(rand); 
     g.fillOval(300 - sizeX1/2, 50 - sizeY1/2, sizeX1, sizeY1);//these six ovals are supposed to increase in size 
     g.fillOval(130 - sizeX2/2,100 - sizeY2/2, sizeX2, sizeY2); 
     g.fillOval(480 - sizeX3/2,100 - sizeY3/2, sizeX3, sizeY3); 
     g.fillOval(130 - sizeX4/2,400 - sizeY4/2, sizeX4, sizeY4); 
     g.fillOval(480 - sizeX5/2,400 - sizeY5/2, sizeX5, sizeY5); 
     g.fillOval(305 - sizeX6/2,450 - sizeY6/2, sizeX6, sizeY6); 


     try 
     { 
      Thread.sleep(100); 
     } 
     catch(InterruptedException e) 
     { 
      e.printStackTrace(); 
     } 
     inc(); 
    } 


    private void inc()//increase the size of the ovals 
    { 

      sizeX1++; 
      sizeY1++; 
      sizeX2++; 
      sizeY2++; 
      sizeX3++; 
      sizeY3++; 
      sizeX4++; 
      sizeY4++; 
      sizeX5++; 
      sizeY5++; 
      sizeX6++; 
      sizeY6++; 
      repaint(); 

    } 


    public static void main(String[] args) {} 
+1

當兩個圓碰撞,他們的中心之間的距離等於他們的半徑之和。另外,如果你創建了一個'Circle'類,你的代碼將會大大改善。 – Blender

+0

*「請不要將其作爲複本關閉。」*當然。但既然你基本上拋棄了代碼,並要求我們爲你完成它,我會投票結束「不是真正的問題」。 –

+0

我會在Circle類中包含什麼? – imulsion

回答

3

計算圓是否重疊並不難。一旦兩個圓的半徑的總和變得等於或大於它們的中心點之間的距離,則兩個圓將具有重疊。

把那些到谷歌提供了所需的公式:

旁邊的是,一些言論有關代碼

  • 覆蓋的paintComponent方法來代替的paint方法
  • 不是請致電Thread.sleep事件調度線程因爲這會阻止用戶界面。我的猜測是,用現在的代碼,你永遠不會看到重畫。有關更多信息,請參閱Concurrency in Swing教程。你想要做什麼的解決方案是使用搖擺Timer