boid/Boid.java
2020-06-27 15:44:16 +02:00

41 lines
1.1 KiB
Java

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
public class Boid extends PhysicsObject implements Drawable {
public Boid(int width, int height) {
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);
}
@Override
public void draw(Graphics g) {
g.fillOval((int) x, (int) y, 2, 2);
}
@Override
public void simulate() {
super.simulate();
ArrayList<PhysicsObject> others = ChunkManager.get_objects((int) x, (int) y);
if (others.size() == 0)
return;
for (PhysicsObject o : others) {
double dist = this.get_sqr_distance(o);
if (dist < 500 && dist > 20) {
// Rule 1: collect in groups
this.apply_force(o.x - x, o.y - y, (float) Math.min(0.005 / dist, 1));
this.apply_force(o.v_x, o.v_y, 0.005f);
} else if (dist < 20) {
// Rule 2: keep distance
this.apply_force(x - o.x, y - o.y, (float) Math.min(0.005 / dist, 1));
}
}
}
}