I am new to Java game programming, but I’ve done a bit of Allegro, so I thought it could be fun trying a bit of Java ;D
I decided to make a small program with a sliding ball to get vsync in order…
Here is the code:
import java.applet.;
import java.awt.;
import java.awt.geom.;
import java.awt.image.;
import java.awt.image.BufferStrategy;
import java.awt.Graphics2D.;
import java.util.;
public class PlayingField extends Applet{
public void init() {
setLayout(new BorderLayout());
add(new PField());
}
}
class PField extends Canvas {
PaintTimer pt;
Timer t;
int x;
BufferedImage bi;
Graphics2D big;
Rectangle area;
BufferStrategy strategy;
boolean firstTime = true;
boolean increasing = true;
public PField() {
x = 0;
pt = new PaintTimer();
t = new Timer();
t.scheduleAtFixedRate(pt,200,10);
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
if(firstTime) {
Dimension d = getSize();
area = new Rectangle(d);
bi = (BufferedImage)createImage(d.width,d.height);
big = bi.createGraphics();
createBufferStrategy(3);
strategy = getBufferStrategy();
firstTime = false;
}
Graphics2D g2d = (Graphics2D)strategy.getDrawGraphics();
g2d.setColor(Color.white);
g2d.clearRect(0,0,area.width,area.height);
g2d.setColor(Color.red);
g2d.fill(new Ellipse2D.Double(x,50,32,32));
strategy.show();
g2d.dispose();
}
class PaintTimer extends TimerTask {
public void run() {
if(x+32>=area.width && increasing==true)
increasing = false;
if(x<=0 && increasing==false)
increasing = true;
if(increasing)
x = x + 2;
else
x = x - 2;
repaint();
}
}
}
Here vsync seems to be ok, however the speed is not constant. Why is that, is there any timing method which is more constant than TimerTask?
I have tried to remove Graphics g from update, which I should be able to as update don’t use g at all. But that really messes up things. The vsync goes completely, so as well as speed problems I also get flickering!
Why is that?
Could anybody pls enlighten me 8)