I am writing a window in which circles \ squares must constantly move. Only circles \ squares are shown, but at this time other figures are moving.
(here's the source git: https://github.com/Kaper156/MovingFigures )
I decided to add classes of standard shapes (MovingCircle, MovingSquare) and implement in them the direction and calculation of the next point (as well as the change of direction in the collision).
The problem is this: I had to write two almost identical classes (MovingCircle, MovingSquare) , which complement Ellipse2d.Double and Rectangle2d.Double respectively. How to make common for these two classes "shifter"? After all, the coordinates and dimensions I need are available only in the latest implementation.
public class MovingSquare extends Rectangle2D.Double implements MovingFigure { private float angle; public Color color; MovingSquare() { Random r = new Random(); this.width = this.height = r.nextInt(20) + 5; this.angle = r.nextFloat() * 360; this.x = width * 3 + r.nextDouble() * (CANVAS_W - width * 6); this.y = height * 3 + r.nextDouble() * (CANVAS_H - height * 6); this.color = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } public void MoveSelf() { x = x + Math.cos(angle * Math.PI / 180) * SPEED; y = y + Math.sin(angle * Math.PI / 180) * SPEED; if (x <= this.width || x >= CANVAS_W - width * 2) { angle = 180 - angle; } if (y <= this.height || y >= CANVAS_H - height * 2) { angle = 360 - angle; } } } public class MovingCircle extends Ellipse2D.Double implements MovingFigure { private float angle; public Color color; MovingCircle() { Random r = new Random(); this.width = this.height = r.nextInt(20) + 5; this.angle = r.nextFloat() * 360; this.x = width * 3 + r.nextDouble() * (CANVAS_W - width * 6); this.y = height * 3 + r.nextDouble() * (CANVAS_H - height * 6); this.color = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } public void MoveSelf() { x = x + Math.cos(angle * Math.PI / 180) * SPEED; y = y + Math.sin(angle * Math.PI / 180) * SPEED; //TODO radius if (x <= this.width || x >= CANVAS_W - width * 2) { angle = 180 - angle; } if (y <= this.height || y >= CANVAS_H - height * 2) { angle = 360 - angle; } } }