Reputation: 425
I tried to make a simple game in Java and ended up with this code
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
}
...
while (true) {
repaint();
Thread.sleep(10);
}
It redraws not frequently enough. But if I move my mouse on top of the window it starts to repaint much more frequently. Pressing buttons on keyboard speeds up too.
I'm using Arch with i3wm
.
Upvotes: 2
Views: 463
Reputation: 26809
I had exactly the same problem. Two timers didn't work for me. I managed to move an object smoothly by adding rendering hints and drawing an empty rectangle before my main object:
public void paintComponent(Graphics g) {
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE)
g2d.fillRect(0, 0, getWidth, getHeight)
// paint your object here
}
Upvotes: 0
Reputation: 425
Don't trust guides on the internet. Think yourself sometimes.
It was the guide with mistake. The problem is that the algorithm is wrong. We just have to draw more frequently than update our world.
Here is a stupid implementation of this. It should may be really wrong in terms of concurrency.
Timer timer1 = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.repaint();
}
});
timer1.start();
Timer timer2 = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.move();
}
});
timer2.start();
Upvotes: 1