I am a mildly experienced programmer who has created several game engine templates and small 2d games in Java. I am currently expanding to 3d game engines and am re-writing a previous engine to be more adaptive and Object-oriented.
My issue is, and has been periodically, that the objects are only sometimes rendered. This causes me to have to constantly re-run the program just to display any images.
I have not found any direct answers to this question, and nobody else seems to have this same issue (even when observing sources with the exact same code setup). The problem apparently lies within the render() method sometimes not properly creating or utilizing the Graphics & BufferStrategy objects while inside a thread called from the main method.
Here is some code of the 'Main' class:
public Main() {
addScreenAndFrame();
}
public static void main(String[] args) {
main = new Main();
frame.add(main);
thread = new Thread(main);
running = true;
thread.start();
}
public void run() {
while (running) {
render();
tick();
}
}
public void tick() {
screen.tick();
}
public void render() {
bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
screen.paintComponent(g);
g.dispose();
bs.show();
}
Here is some code from the Screen class:
public Screen(int width, int height) {
this.width = width;
this.height = height;
addEntities();
}
public void paintComponent(Graphics g) {
p.render(g);
}
public void tick() {
KeyInput.tick();
renderInput();
}
public void addEntities() {
p = new PolygonObject(new double[] {50,200,50}, new double[] {50,200, 200} );
}
And finally here is the PolygonObject class:
public PolygonObject(double x[], double y[]) {
Screen.polygonSize ++;
polygon = new Polygon();
for (int i=0; i < x.length; i++) {
polygon.addPoint((int)x[i], (int)y[i]);
}
}
public void render(Graphics g) {
g.fillPolygon(polygon);
g.setColor(Color.black);
g.drawPolygon(polygon);
}
I don't know why calling render() while within a thread would yield inconsistent results when drawing images to the screen. I have seen many source codes for game templates and tutorials with the exact same code without any rendering issues. The only way rendering works consistently is when I draw images with the paintComponent() method of the Canvas class outside of a thread which limits my program functionality and is poor design of a game engine.
I would like an explanation of this and any possible solutions. There is NO accurate way for me to build the game engine without the use of a thread in order to have controlled time-based functionality.