import java.awt.Graphics; import java.util.ArrayList; import java.util.Random; public class Boid extends PhysicsObject implements Drawable { private int group; public Boid(int width, int height, int group) { super(0, 0, 0, 0); Random r = new Random(); this.x = r.nextInt(width); this.y = r.nextInt(height); this.apply_force(r.nextFloat() * 2 - 1, r.nextFloat() * 2 - 1, 1); this.group = group; } @Override public void draw(Graphics g) { g.fillOval((int) x, (int) y, 2, 2); } public void simulate(int group) { super.simulate(); // Gruppen werden zeitversetzt aktualisiert um die Performance zu verbessern if (this.group != group) return; ArrayList others = ChunkManager.get_objects((int) x, (int) y); int other_count = others.size(); if (other_count == 0) return; for (int i = 0; i < other_count; i++) { // Überprüfung teilweise überspringen, wenn es zu viele objekte in der Nähe gibt if ((i + group) % Math.max(1, other_count / 16) != 1) continue; PhysicsObject o = others.get(i); double dist = this.get_sqr_distance(o); if (dist < 500 && dist > 20) { // Regel 1: Zu anderen hin bewegen this.apply_force(o.x - x, o.y - y, (float) Math.min(0.005 / dist, 1)); // Regel 3: In die Richtung der anderen fliegen this.apply_force(o.v_x, o.v_y, 0.005f); } else if (dist < 20) { // Regel 2: Abstand halten this.apply_force(x - o.x, y - o.y, (float) Math.min(0.005 / dist, 1)); } } } }