在java中用圆圈进行碰撞检测

时间:2012-08-26 07:33:12

标签: java collision-detection 2d-games

有很多像这样的问题,但是我把它们都检查出来了,没有一个能解决我的问题,所以请不要将它作为副本关闭。

我正在制作一个中间有一个大圆圈的游戏,周围是其他六个圆圈,这些圆圈的尺寸逐渐增大。如果六个圆圈中的一个与中心圆相撞,我想结束游戏。任何人都可以提供合适的解决方案吗?

这是我的代码:

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 个答案:

答案 0 :(得分:3)

计算圆是否重叠并不那么困难。只要两个圆的半径之和等于或大于它们的中心点之间的距离,就会有2个圆重叠。

将这些内容放入Google会提供所需的公式:

接下来,有关您的代码的一些评论

  • 覆盖paintComponent方法而不是paint方法
  • 事件调度线程上调用Thread.sleep,因为这会阻止用户界面。我的猜测是,使用当前代码,您将永远不会看到重绘。有关更多信息,请参阅Concurrency in Swing教程。您想要做的解决方案是使用Swing Timer
相关问题