Proper method to update and draw from game loop?

Posted by Lost_Soul on Game Development See other posts from Game Development or by Lost_Soul
Published on 2013-07-16T01:14:32Z Indexed on 2013/11/13 10:12 UTC
Read the original article Hit count: 263

Filed under:
|
|
|
|

Recently I've took up the challenge for myself to create a basic 2d side scrolling monster truck game for my little brother. Which seems easy enough in theory. After working with XNA it seems strange jumping into Java (which is what I plan to program it in).

Inside my game class I created a private class called GameLoop that extends from Runnable, then in the overridden run() method I made a while loop that handles time and such and I implemented a targetFPS for drawing as well. The loop looks like this:

    @Override
    public void run()
    {
        long fpsTime = 0;

        gameStart = System.currentTimeMillis();
        lastTime = System.currentTimeMillis();

        while(game.isGameRunning())
        {
            currentTime = System.currentTimeMillis();

            long ellapsedTime = currentTime - lastTime;

            if(mouseState.leftIsDown)
            {
                que.add(new Dot(mouseState.getPosition()));
            }

            entities.addAll(que);

            game.updateGame(ellapsedTime);

            fpsTime += ellapsedTime;
            if(fpsTime >= (1000 / targetedFPS))
            {
                game.drawGame(ellapsedTime);
            }

            lastTime = currentTime;
        }

The problem I've ran into is adding of entities after a click. I made a class that has another private class that extends MouseListener and MouseMotionListener then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great but when I add the entity it throws a CME (Concurrent Modification Exception) sometimes. I have all the entities stored in a LinkedList so later I tried adding a que linkedlist where I later add the que to the normal list in the update loop.

I think this would work fine if it was just the update method in the gameloop but with the repaint() method (called inside game.drawGame() method) it throws the CME.

The only other thing is that I'm currently drawing directly from the overridden paintComponent() method in a custom class that extends JPanel.

Maybe there is a better way to go about this? As well as fix my CME?

Thanks in advance!!!

© Game Development or respective owner

Related posts about java

Related posts about game-loop