mardi 25 avril 2017

Java Random Circles

I am new in Java. I want to make simple agario game for my project. But I have a problem. I want to make random stopping circles on Panel but my circles don't stop and changing.

The Problem is I think Timer.

class TestPanel extends JPanel implements ActionListener{
TestPanel(){
    Timer t = new Timer(50,this);  
    t.start();
}

Random rnd = new Random();


int r = rnd.nextInt(256);   
int b = rnd.nextInt(256);
int gr = rnd.nextInt(256);

Color randomColor = new Color(r,b,gr);

Ellipse2D.Double ball = new Ellipse2D.Double(0, 0, 40, 40);   
double v = 10;  
public void paintComponent(Graphics g){
    super.paintComponent(g); 

    Graphics2D g2 =(Graphics2D)g;


    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);


    g2.setColor(Color.RED);
    g2.fill(ball);    

    int NumOfCircles = 70;  
    int diameter;
    int x, y;


    Graphics2D g3 =(Graphics2D)g;



    for(int count = 0; count < NumOfCircles; count++){
        diameter = rnd.nextInt(10);
        x = rnd.nextInt(600);
        y = rnd.nextInt(620);
        g3.setColor(randomColor);
        g3.fillOval(x, y, diameter, diameter);
    }

    }


@Override
public void actionPerformed(ActionEvent arg0) {
    Point p = getMousePosition();
    if(p==null) return;
    double dx = p.x - ball.x - 20;
    double dy = p.y - ball.y - 20;
    if(dx*dx+dy*dy >12){
    double a=Math.atan2(dy, dx);
    ball.x += v * Math.cos(a);
    ball.y += v * Math.sin(a);}
    repaint();
}

}




Aucun commentaire:

Enregistrer un commentaire