0

I'm creating a flappy bird kind of game. The fist step was to setup a Frame, panel in the main class and a Player class that extends JLabel. In this class, I've created a fall() method that sets the players y location to + 7. Then I created a gameLoop which works with delta. If delta >= 1 I call ufo.fall() and set delta --;.

Now, when I run my game, It lags immensely. it becomes more over time. Do you have an idea why this is?

This is my code: Main class:

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

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

public class Main implements KeyListener{

    static Player ufo = new Player(100, 100, 40, 50, Color.BLUE);
    private static long fps = 30;
    public static boolean jumpbool;  
    
    public static void main(String[] args) throws InterruptedException {
        
        JFrame frame = new JFrame();
        frame.setSize(4000, 2000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);
        frame.setLayout(null);
        
        JPanel panel = new JPanel();
        panel.setSize(4000, 2000);
        panel.setLayout(null);
        panel.setBackground(Color.darkGray);
        
        panel.add(ufo);
        
        frame.add(panel);
        
        frame.setLocationRelativeTo(null);
        frame.setVisible(true); 
        
        frame.addKeyListener(new Main());
        
        runLoop();
        
    }
    
    public static void runLoop() {
    
        double drawInterval = 1000000000/fps;
        double delta = 0; 
        long lastTime = System.nanoTime();
        long currentTime;
        
        while(true) {
            
            currentTime = System.nanoTime();
            
            delta += (currentTime - lastTime) / drawInterval; 
            
            lastTime = currentTime;
            
            if(delta >= 1) {
                ufo.fall();
                delta --;
            }
        }
    }

Player class:

import java.awt.Color;

import javax.swing.JLabel;

public class Player extends JLabel{

    int x,y,width,height;
    Color color; 
    
    Player(int x, int y, int width, int height, Color color){
        
        this.setBounds(x, y, width, height);
        this.setBackground(color);
        this.setOpaque(true);
    }
    
    public void fall() {
    
        this.setLocation(this.getX(), this.getY() + 7);
        
    }
}
AnsG
  • 5
  • 5
  • Does this answer your question? [Why does my custom Swing component repaint faster when I move the mouse? (Java)](https://stackoverflow.com/questions/57948299/why-does-my-custom-swing-component-repaint-faster-when-i-move-the-mouse-java) – Progman Nov 06 '22 at 13:56
  • @Progman. It maybe does. But I cannot seem to apply it to my code. Can you help me there? I can see that the problem seems to be similar but I can't apply that to my code. – AnsG Nov 06 '22 at 17:05

0 Answers0