FPS limit for my game

Ok, I’m doing a little game, and I need to limit FPS, because when I play on my really fast computer, I have about 850 FPS and the game will go, REALLY fast, and when I switch to my old computer, it goes much slower, so I need to limit FPS to get this right. How to limit my FPS? My main game loop:

    public void startGame(){
    initialize();
    while(true){
        drawScreen();
        drawBuffer();
        plyMove();

        //FPS counter
        now=System.currentTimeMillis(); 
        framesCount++; 
        if(now-framesTimer>1000){
            framesTimer=now; 
            framesCountAvg=framesCount; 
            framesCount=0; 
        }

        try{
            Thread.sleep(14);
        }catch(Exception ex){}
    }
}

How do I draw a screen and draw all the other things, players, ball, etc. The game is a remake for pong, by the way.

    public void drawBuffer(){
    Graphics2D g = buffer.createGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(0,0,600,500);
    g.setColor(Color.GREEN);
    g.fillRect(ply1.getX(),ply1.getY(),ply1.getWidth(),ply1.getHeight());
    g.setColor(Color.RED);
    g.fillRect(ply2.getX(),ply2.getY(),ply2.getWidth(),ply2.getHeight());
    g.setColor(Color.WHITE);
    g.fillOval(ball1.getX(),ball1.getY(),ball1.getWidth(),ball1.getHeight());
    g.drawString("" + framesCountAvg,10,10);
}

public void drawScreen(){
    Graphics2D g = (Graphics2D)this.getGraphics();
    g.drawImage(buffer,0,0,this);
    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}
+3
source share
6 answers

, . , . , , . , , .

+4

, FPS, , , fps .

, , , . , . , .

+2

, - , , -

while (1)
{
    drawscene();
    update();
}

, 0,17 . 60 , , 850 14 (0,17 * 850), , .

elapsed = 0;
while (1)
{
   start = time();
   update(elapsed); 
   drawscene();
   sleep(sleeptime);
   end = time();

   elapsed = end - start;
}
+1

, . plyMove(); , -

plyMove() {
    ply1.x += amountX;
    ply1.y += amountY;
}

plyMove(double timeElapsed) {
    ply1.x += amountX * timeElapsed;
    ply1.y += amountY * timeElapsed;
}

timeElapsed , .

double timePrev = System.currentTimeMillis();
while(true) {
    double timeNow = System.currentTimeMillis();
    double elapsed = timeNow - timePrev;

    drawScreen();
    drawBuffer();
    plyMove(0.001 * elapsed);

    timePrev = timeNow;
}
0

, :

float timer = 0;
float prevTime= System.currentTimeMillis();
while(true)
{
    draw();

    float currentTime = System.currentTimeMillis();
    timer += currentTime - prevTime;

    while (timer > UPDATE_TIME) // To make sure that it still works properly when drawing takes too long
    {
        timer -= UPDATE_TIME;
        update();
    }
}

Where UPDATE_TIME is in what interval that you want to update in milliseconds.

0
source

One of the methods:

try {
    Thread.sleep(20);
} catch(InterruptedException e) {}

at the end of the main loop. Adjust the quantity according to your needs.

-3
source

All Articles