I am creating a program to simulate an outbreak. The program will have a number of circles bouncing around the screen. I have a class for the window and a class for the entities. I create instances of the class and add them to an ArrayList. I cannot find out how to add the collision detection. Do I add it to the entity class? or to the "driver" class that runs the frame.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFrame;
public class Simulation {
static ArrayList<Entity> people = new ArrayList<Entity>();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Number for the population");
int population = scan.nextInt();
JFrame frame = new JFrame("Outbreak");
frame.setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i=0; i<population;i++) {
frame.setVisible(true);
Random rand = new Random();
int xPos = rand.nextInt(900)+50;
int yPos = rand.nextInt(900)+50;
if (i==0) {
Entity person = new Entity(xPos, yPos, true);
frame.add(person);
people.add(person);
}else {
Entity person = new Entity(xPos, yPos, false);
frame.add(person);
people.add(person);
}
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Timer;
import javax.swing.JComponent;
public class Entity extends JComponent implements ActionListener{
private int xPos;
private int yPos;
private int size = 20;
private boolean patientZero;
private boolean carrier;
Timer tm = new Timer(5, this);
private int xVel = 2;
private int yVel = 2;
public Entity(int xPos, int yPos, boolean zero) {
this.xPos = xPos;
this.yPos = yPos;
if (zero) {
patientZero = true;
}else {
patientZero = false;
}
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (patientZero) {
g2.setColor(Color.RED);
}else {
g2.setColor(Color.BLUE);
}
g2.drawOval(this.xPos, this.yPos, size, size);
g2.fillOval(this.xPos, this.yPos, size, size);
tm.start();
}
public int getX() {
return xPos;
}
public int getY() {
return yPos;
}
public boolean checkCollision() {
return false;
}
public void actionPerformed(ActionEvent e) {
if (xPos < 0 || xPos > 950) {
xVel = -xVel;
}
if (yPos < 0 || yPos > 800) {
yVel = -yVel;
}
xPos = xPos+xVel;
yPos = yPos+yVel;
if (checkCollision()) {
xVel = -xVel;
yVel = -yVel;
}
repaint();
}
}
Any help is greatly appriciated
What I have tried:
I know theres ways to check for collision of ovals (circles in my case) using the pythagorean theorem but I dont know how to check for all circles if that makes sense.