Hi there,
I'm currently working on a smallish tile-based game with my friend, just a little summer project. We're both pretty square in the middle of 'intermediate' level coders, I would guess.
Our game has some fairly meaty algorithms happening, and so we're very cpu-cycle concious. However, as it happens, our algorithms aren't really wasting too much time (yay!), the current greatest offender is...
... drawing graphics!
It's not maxing out a CPU yet, and it's not something that has the chance to balloon as the program grows - as it will only ever be rendering the same number of tiles. It also is responsive enough in-game, so we're not worried, per se, but we'd like to get the time spent there down so we have more room for everything else.
We're clearly not entirely solid on how best to do things in Java, so some help would be greatly appreciated.
The way it's currently implemented, is:
- Everything is eventually drawn to an object which subclasses JPanel, its paintComponent(Graphics g) is overridden, and it also implements Runnable. The run method has a loop which ensures that the object is repaint()'ed regularly.
.... public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; Dimension size = getSize(); // If we're in a game, draw the game if(worlds[currentWorld].currentGame != null){ worlds[currentWorld].currentGame.draw(g2d, size); } } ....- As you can see, we're not drawing straight to the screen. A Graphics2D object is created, and then passed down into the bowels of the game object hierarchy. The Graphics2D object is passed down through many objects' draw() functions until it gets all the way down to a Sprite. Here, the actual g.drawImage(...) is called. This is the function that takes all the time:
Where image is an Image member variable of whichever Sprite is being drawn, and width and height are some power of 2 indicating the size of tiles.public void draw(Graphics2D g, int x, int y){ // Convert x and y from number of tiles to pixels x *= width; y *= height; g.drawImage(image, x, y, null); }
This may seem like some kind of weird hodgepodge of terrible, if so - it is because I have read many tutorials on the subject of drawing in java, all of which are no newer than 2005 and all of which seem to do things a different way. Also, I am just now revisiting the graphics methods after several months where I have been busy, so things have become stale in my mind.
If anyone has any tips or would like to point out some glaring flaws, feel free to do so - it would be greatly appreciated.