I'm making a 2D game similar to mario in Java.
I have some questions about class organization and proper method usage.
I have the following classes:
- Main: runs the game in a JFrame
- GamePanel: JPanel with boundary rules, timer, paintComponent, scoring, keyboard input, collision check
- Player: only knows about its own attributes... has getter and setter methods for
x, y
location,height, width, weight
etc... - Item: Same thing as
Item
class... this class will be used for items in the game, like bullets, cars, etc... - Physics: I was going to use this class to contain all actions for all items in the game (items class, player class, etc)... Like the rules for jumping, or running, etc...
Am I using the classes appropriately? I'm not sure whether each class should contain its own unique methods...
For example, only Player
class objects will be able to jump and run... So should Player class have jump()
and run()
methods? Or should it just have setX()
, setY()
methods which alter its location based on run()
from another class like Physics()
?
And for a gun, I have shoot()
which creates a new Item
bullet = new Item(this, player.getX(), player.getY()+40, 25, 10, 10, bulletVelX, 0);
But as you can see below, I'm actually moving the bullet via the timer()
class by calling the Item class's autoMove()
method to change the bullet Item's location.
I'm also confused on the correct usage of timer():
I'm using it to run methods at a certain interval if a given boolean
is set true...
public void timer() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
collisionCheck();
if (jump) {
player.jump(velocityX, -velocityY);
velocityY--;
checkPlayerBounds(player);
repaint();
}
if (shoot) {
if (!bulletMag.isEmpty()) {
for (Item bullet : bulletMag) {
bullet.autoMove(bullet.getVelocityX(), bullet.getVelocityY());
}
if (bulletMag.size() > 30) {
bulletMag.clear();
}
repaint();
}
}
}
}, 0, 100);
}
Is is okay to put all that logic inside the timer class? Or should the timer class be kept as clean and empty as possible? Is that where my main Game loop is?
Lastly, paintComponent():
I put a paintComponent in each class (Player, Item, and GamePanel so far), and paint them by calling them from within the GamePanel's paintComponent. Is that right?
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
player.paintComponent(g);
for (Item bullets : bulletMag) {
bullets.paintComponent(g);
}
}
So, in summary is my usage of classes, timer, and paintComponent correct?