I am writing a simple asteroid clone game using Swing to display graphics. I kind of follow the lessons of Derek Banas , but decided to expand myself.
The initial idea is that every graphic element in the game (i.e. asteroids, spaceship and bullets) extends the
Polygon class. Their constructor will look something like this:
public class SpaceShip extends Polygon {
And it will be similar to other graphic elements.
EDIT: The key element here is that the two arrays do not preserve the actual coordinates of the objects, but their position relative to their center, the coordinates of which are double -type class-variable. Thus, arrays describe only the shape of the object, while the subclass method move() will affect the central coordinates. The class responsible for the actual drawing will call the move() method, and then apply the affine transformation to move and rotate the shape (according to the specified angle parameter). I do this to avoid the exact problems associated with working with double arithmetic.
Now, since the elements share many βequalβ variables (their center coordinates, which I need to translate them with affine transformation, their speed components, etc.) and methods (getters and setters, move() , etc. ) I was thinking of making them an extension of an abstract class β say, GameShape β that contains all these common methods and variables. GameShape will now be as follows: 21> 21>
public abstract class GameShape extends Polygon {
Then I would like to set the desired value to polyXArray and polyYArray when I define different subclasses to draw the different shapes that I need, but I could not find a way to do this.
I want these variables to be static, because they are specific properties of individual classes, and I would not want to pass them as a parameter every time I create a new object.
My situation is very similar to the one described in this question , but the proposed solution does not seem to work, since I need the same variables in the constructor, is there a way to overcome - or around - this problem? Regardless of the procedure, my main goal is to have a superclass common to all graphic elements in order to avoid dozens of lines of code with copying.