The last post of this game development series, I showed you a basic example ShowFPS application that uses a technique called passive rendering.
So In this post, I am gonna show you another example for Active Rendering. The ShowFPS class from the previous post, have to be changed to have an active rendering technique.
How to implement active rendering?
The previous ShowFPS application redraws itself in the paint() method but it is the swing library that decides when to call that method.
The event dispatch thread handles the rendering of the swing components and it is out of your hand. This is fine for normal applications, it is not recommended for the game though.
Instead of using event dispatch thread to draw frames, I would rather use a game thread to handle the rendering in a loop on which we shall have full control.
To achieve this ShowFPS class implements the Runnable interface and The game thread will be created and launched from the creatAndShowGUI() method.
While the variable running is true gameThread will be running. Notice that the running is volatile to stop the JVM from making a separate copy of running variable in other thread (Which makes changes on it: EDT) due to optimization purpose.
So this way changing the variable' s value from other thread will be known to the game thread.
For this application, I didn't use setDefaultCloseOperation() to stop the application instead I added a windowLinstener to stop it.
Whenever the window is going to close this event, will trigger the shutDown method. This method runs on the EDT and it writes false to running. Before exiting the program it waits for the gameThread to stop.
See code snippet here
The code for updated ShowFPS (ShowFPS to ActiveRendering) application.
Why the fps text is flickering?
If you run the app you see the fps text is flickering. This is because you are seeing two processes first one is clearing the screen with black colour and second is redrawing the contents.
It can be solved if we don't show the rendering process to the user. I mean we will show only the complete image so the user can't see any the rendering process.
And it is the topic for the next post.
Thanks for reading this one.
follow this blog and do comment if you have any suggestions.
No comments:
Post a Comment