简体   繁体   中英

How to make graphics appear at random and disappear on collision with another graphic?

I have written some code on moving a graphics (that is surrounded by a rectangle), and I am trying to draw another oval (with a rectangle around it) that will generate at random. Right now, it's generating WAY fast, and I don't want to use Thread.sleep; because it will stop listening for the keys (to my knowledge?). So is anyone good with multi-threading that could help me do this or know how to make a graphic appear until it is touched by the movable graphic.

The Graphics Generator in main class:

public void paintComponent(Graphics g){
    //System.out.println("X = " + al.x + ", Y = " + al.y);
    boolean intersect = false;
    int points = 0;

    g.drawString("Points: " + points, 5, 445);

    Rectangle r1 = new Rectangle(al.x, al.y, 10, 10);
    g.setColor(Color.BLACK);
    g.fillOval(al.x, al.y, 10, 10);

    Random randX = new Random();
    Random randY = new Random();
    int xInt = randX.nextInt(590);
    int yInt = randY.nextInt(440);

    Rectangle dCoin = new Rectangle(xInt, yInt, 10, 10);
    g.setColor(Color.YELLOW);
    g.fillOval(xInt, yInt, 10, 10);


        /*
         * (???)
         * 
         * for(int idx = 1; idx == 1; idx++){
         *      if(xInt < 590 && yInt < 440){
         *      }
         *  }
         *
         * Check if graphic collides with another:
         * 
         * if(r1.intersects(r2)){
         *      doSomething;
         * }
         *
         */
        repaint();
    }

}

BTW: r1 surrounds the movable graphic, and r2 is the rectangle surrounding the randomly generated graphic. I had to make invisible rectangles around the ovals to get the r1.intersects(r2) method.

You should use the Swing Timer class to periodically generate ActionEvent s on the Event Dispatch Thread. This avoids the problem of the application becoming unresponsive to keystrokes and other user input.

The actionPerformed callback is the hook into your routing to move and repaint the object(s) you wish to animate. Within the animation routine you can record the time ellapsed since the last time the method was called in order to maintain the desired velocity.

Timer timer = new Timer(1000, new ActionListener() {
  long lastTime = System.currentTimeMillis();

  public void actionPerformed(ActionEvent evt) {
    long timeNow = System.currentTimeMillis();
    long timeEllapsed = timeNow - lastTime;
    lastTime = timeNow;

    if (timeEllapsed > 0L) {
      for (Moveable mv : moveables) {
        mv.updatePosition(timeEllapsed);
      }

      for (Drawable d : drawables) {
        d.repaint();
      }
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM