0

I am just a beginner and was doing some time with games and got a problem

package minigames;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class fallingball extends JPanel {


   int x = 250;
   int y = 0;

   private void moveBall() {
      y = y + 1;


   }


   public void paint(Graphics g){
      super.paint(g);
      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.setColor(Color.black);
      g2d.fillOval(x, y, 30, 30);
   }

   public static void main(String[] args) throws InterruptedException{
      JFrame f = new JFrame("Falling Ball");
      fallingball game = new fallingball();
      f.add(game);
      f.setSize(500, 500);
      f.setResizable(false);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      while (true) {
         game.moveBall();
         game.repaint();
         Thread.sleep(10);
      }
   }

}

only 1 ball is generated and it gets fallen down. i wanted to generate balls falling randomly and from different x co-ordinate in the frame how can i do that

4

1 回答 1

0

那么对于你想要的随机 x

import java.util.Random();

并使用

Random rnd = new Random();
x = rnd.nextInt(<HIGHEST X VALUE POSSIBLE>)+1;

这将生成一个从 0 到最大 X 值的随机整数并将其分配给 x。注意(它是 +1,因为 rnd.nextInt(n) 创建了一个从 0 到 n-1 的值。
要让更多的球继续下落,请在循环中尝试以下操作:

while (true) {
     game.moveBall();
     game.repaint();
     Thread.sleep(10);
     if (y >= <MAX y>) {
      y = 0;
      x = rnd.nextInt(<max x>)+1;
    }
  }

你只需要在它离开屏幕时重置 y ,否则它只会越来越低而不可见。这是一个快速的解决方案。理想情况下,您会在屏幕外使用对象并创建/销毁它们,这将使只有 1 个保持随机下降。根据需要进行调整。

也请在这里阅读游戏循环:
http ://www.java-gaming.org/index.php?topic=24220.0

while (true)

是一个非常糟糕的游戏循环

于 2013-08-16T13:21:47.033 回答