import java.awt.Point; import java.util.ArrayList; import geofasc.swing.Circle; import geofasc.swing.tool.Calculator; import geofasc.swing.tool.Canvas; /** * Eine Bullet kann sich mit einer Geschwindigkeit von 5 Pixeln * in eine bestimmbare Richtung bewegen. Sie ist ein {@link Circle} und * wird auf einer {@link Canvas} visualisiert. * */ public class Bullet extends Circle { private static final int sVelocity = 5; // Konstante Geschwindigkeit aller Bullets in Pixeln private Canvas mCanvas; private ArrayList mNeighbours; // Liste benachbarter Bullets /** * Erzeugt eine neue Bullet bullet. * * @param x die x-Koordinate von bullet bez. der canvas * @param y die y-Koordinate von bullet bez. der canvas * @param diameter der Radius des Kreises zur Visualisierung von bullet * @param direction die initiale Richtung von bullet * @param canvas die Zeichenflaeche, die bullet visualisiert */ public Bullet(int x, int y, int diameter, double direction, Canvas canvas) { super(x, y, diameter); setFigureDirection(direction); mCanvas = canvas; mCanvas.add(this); mNeighbours = new ArrayList(); } /** * Bewegt diese bullet um 5 Pixel abhängig * von ihrer Bewegungsrichtung. */ public void move() { int x = getFigureLocationX(); int y = getFigureLocationY(); double dir = getFigureDirection(); if (y <= 0 || (y + getFigureHeight()) >= mCanvas.getHeight()) setFigureDirection(360 - dir); if (x <= 0 || (x + getFigureWidth()) >= mCanvas.getWidth()) setFigureDirection(180 - dir); for (Bullet b : mNeighbours) { if (hits(b)) { setFigureDirection(dir - 180); } } moveFigureLocationBy(sVelocity); } /** * Fuegt die Nachbarbullet b der Liste von Nachbarbullets dieser * bullet hinzu. * * @param b die Nachbarbullet */ public void addNeighbour(Bullet b) { if (b != null && !mNeighbours.contains(b)) mNeighbours.add(b); } /** * Gibt den Mittelpunkt des dieser bullet visualisierenden * Kreises wieder. */ public Point getCenter() { return new Point(getFigureLocationX() + getRadius(), getFigureLocationY() + getRadius()); } /** * Prueft fuer diese bullet, ob sie mit der Bullet b * kollidiert. * * @param b die Nachbarbullet * @return true oder false */ public boolean hits(Bullet b) { if (b == null) return false; else { Point m1 = getCenter(); Point m2 = b.getCenter(); Calculator c = new Calculator(); return (c.sqrt(c.square(m1.x - m2.x) + c.square(m1.y - m2.y)) <= (getRadius() + b .getRadius())); } } /** * Entfernt die Nachbarbullet b aus der Liste von Nachbarbullets dieser * bullet. * * @param b die Nachbarbullet */ public void removeNeighbour(Bullet b) { mNeighbours.remove(b); } }