Ich bekomme keine flüssige Game-Loop hin. Bei mir leggt es immer ein wenig. Weiß jemand woran das liegt?
Java:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameloopTest {
static Img[] img = new Img[20];
static JFrame frame = new JFrame("GameloopTest");
static JPanel contentPane = new JPanel() {
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
for(int i = 0; i < img.length; i++) {
img[i].draw(g);
}
}
};
public static void main(String[] args) throws InterruptedException {
init();
long lastTime = System.currentTimeMillis();
while(true) {
update();
draw();
long thisTime = System.currentTimeMillis();
Thread.sleep(1000/60 - (thisTime - lastTime));
lastTime = System.currentTimeMillis();
}
}
private static void init() {
for(int i = 0; i < img.length; i++) {
img[i] = new Img();
}
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(3);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
private static void update() {
for(int i = 0; i < img.length; i++) {
img[i].update();
}
}
private static void draw() {
contentPane.repaint();
}
private static class Img {
private double x = 0, y = (int)(Math.random() * 400);
private double speed = Math.random() * 5 + 1;
private Image img;
public Img() {
try {
img = ImageIO.read(new File("./res/img.png"));
img = img.getScaledInstance(100, 100, 100);
} catch (IOException e) {
e.printStackTrace();
}
}
public void draw(Graphics g) {
g.drawImage(img, (int)x, (int)y, null);
}
public void update() {
x += speed;
if(x > 800) {
x = -100;
}
}
}
}
[code]
Zuletzt bearbeitet von einem Moderator: