Evtl. sollte ich dann doch erstmal etwas einfacheres machen
Aber das mit dem verschieben ist doch irgendwie komisch. Evtl. hat da ja doch noch jemand einen Idee. Folgende Demo zeigt das Problem in größer:
[HIGHLIGHT="Java"]import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new Test();
}
public static final int SQUARE = 256;
private List<Square> oldSquares;
private Color[] colors;
private Square square;
private int colorIterator;
private boolean gameRunning;
public Test() {
setPreferredSize(new Dimension(SQUARE, 5 * SQUARE / 2));
JFrame frame = new JFrame("Tests");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(this);
frame.pack();
frame.setVisible(true);
doInit();
}
private void doInit() {
gameRunning = true;
colorIterator = 0;
colors = new Color[] { Color.CYAN, Color.YELLOW };
oldSquares = new LinkedList<Square>();
square = new Square(colors[colorIterator++], this);
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
while (gameRunning) {
moveObject();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}
private void moveObject() {
boolean aCollision = false;
for (Square aSquare : oldSquares) {
if (square.intersects(aSquare)) {
aCollision = true;
break;
}
}
if (square.canMove() && !aCollision) {
square.move();
} else {
oldSquares.add(square);
if (square.y <= 0) {
gameRunning = false;
} else {
square = new Square(colors[colorIterator++], this);
if (colorIterator >= colors.length) {
colorIterator = 0;
}
}
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = -1, j = 1; i < getHeight(); i += (SQUARE / 2), j++) {
if (j % 2 == 0) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(SQUARE / 2, i, SQUARE, SQUARE / 2);
}
for (Square aSquare : oldSquares) {
aSquare.draw(g);
}
square.draw(g);
}
class Square extends Rectangle {
private static final long serialVersionUID = 1L;
private Color color;
private int gravity;
private boolean canMove;
private int size;
private Test parent;
public Square(Color theColor, Test theParent) {
super();
color = theColor;
gravity = 1;
canMove = true;
size = SQUARE / 2;
parent = theParent;
x = 0;
y = 0;
width = size;
height = size;
}
public void draw(Graphics theGraphics) {
theGraphics.setColor(color);
theGraphics.fillRect(x, y, size, size);
theGraphics.setColor(Color.BLACK);
theGraphics.drawRect(x, y, size, size);
}
public void move() {
if (y + size + 2 * gravity >= parent.getHeight()) {
stop();
}
y += gravity;
}
public void stop() {
canMove = false;
}
public boolean canMove() {
return canMove;
}
}
}[/HIGHLIGHT]