I'm programming a simple game in java. I've made a collision test with 30 FPS, where I had to get the size of the window. Because I haven't had access to the GUI instance, I thought I'd make a shared instance, because this is pretty standard in Objective-C, where I come from.
class GUI extends JFrame {
private static GUI _sharedInstance;
public static GUI sharedInstance() {
if (_sharedInstance == null) {
_sharedInstance = new GUI();
}
return _sharedInstance;
}
}
But for some reason, it was really slow.
Then I replaced the shared instance with public static final
instances for the size, and it works fast now, even with 60 FPS or higher.
Can anyone explain me why this happens?
EDIT
So instead of calling GUI.sharedInstance().getWidth()
, I'm just calling GUI.windowSize.width
.
I have used the public static final Dimension windowSize
instead.
EDIT
Here's the collision detection.
So, instead of calling int width = GUI.kWindowWidth;
,
I was calling int width = GUI.sharedInstance().getWidth();
before.
// Appears on other side
if (kAppearsOnOtherSide) {
int width = GUI.kWindowWidth;
int height = GUI.kWindowHeight;
// Slow
// int width = GUI.sharedInstance().getWidth();
// int width = GUI.sharedInstance().getHeight();
Point p = this.getSnakeHead().getLocation();
int headX = p.x;
int headY = p.y;
if (headX >= width) {
this.getSnakeHead().setLocation(new Point(headX - width, headY));
} else if (headX < 0) {
this.getSnakeHead().setLocation(new Point(headX + width, headY));
} else if (headY >= height) {
this.getSnakeHead().setLocation(new Point(headX, headY - height));
} else if (headY < 0) {
this.getSnakeHead().setLocation(new Point(headX, headY + height));
}
}