Code locks the window

Asked

Viewed 87 times

-1

I have this code in my game and I check if it’s past 400 milliseconds, and then update.

public void setUpdatePosition(int posicao, long tempo, int posX, int posY) {

    long previous = System.nanoTime();
    Point ponto = new Point(tiles[posicao].x, tiles[posicao].y);
    tiles[posicao].setPosition(posX, posY);

    while(((System.nanoTime() - previous) / 1000000) < tempo) {
        previous = System.nanoTime();
    }
    tiles[posicao].setPosition(ponto.x, ponto.y);
}

But you end up crashing my game, like I fix?

  • 1

    Are you doing everything in a single thread? You could spare the processor using Sleep of Java, not to mention that it would allow another thread to do its work without resource competition

  • 2

    Are you using Swing? If you are, please, read this answer.

1 answer

0

I decided that way, but I don’t know if it’s right.

public void setUpdatePosition(int posicao, long tempo, int posX, int posY) {

        Point ponto = new Point(tiles[posicao].x, tiles[posicao].y);
        tiles[posicao].setPosition(posX, posY);

        thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(tempo);
                    tiles[posicao].setPosition(ponto.x, ponto.y);
                } catch (InterruptedException e) {}
            }

        });

        thread.start();
    }
  • Nwo, it’s not right, especially if it’s in swing. Read the link passed by us comments by @Victorstafusa.

  • I’m not sure about that. I’m already using a thread in my Jpanel() class, which controls gameLoop(), where it’s rendered and controlled the movement of characters and enemies.

  • Have you read the comments link?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.