Reputation: 3
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
Upvotes: 0
Views: 68
Reputation: 108
Well for the random x you want to
import java.util.Random();
and use
Random rnd = new Random();
x = rnd.nextInt(<HIGHEST X VALUE POSSIBLE>)+1;
That will make a random integer from 0 to the max X value and assign it to x. NOTE (it's +1 because rnd.nextInt(n) creates a value from 0 to n-1.
To get more balls to keep falling try this in your loop:
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
if (y >= <MAX y>) {
y = 0;
x = rnd.nextInt(<max x>)+1;
}
}
You just need to reset the y when it goes off screen, otherwise it's just falling lower and lower without being visible. This is a fast solution. Ideally you would use objects and create/destroy them when off screen, this will make only 1 keep falling randomly. Adjust it as needed.
Also please read here for a game loop:
http://www.java-gaming.org/index.php?topic=24220.0
while (true)
is a pretty bad gameloop
Upvotes: 0