Mark Webster
YaBB Newbies
Offline
Posts: 12
Re: Calculating distance between two objects
Reply #6 - Jan 29th , 2010, 6:27am
Ok, I bet you knew this question was coming didn't you? Well, I don't really have a question here, rather I'm pulling my hair out trying to get my head around implementing an array of agents with this code. I don't understand what I'm doing wrong after many a search...clueless I am! int numAgents = 5; Agent[] ag = new Agent [numAgents]; float x; float y; float angle = 0.0; // Direction of motion float speed = 1.4; // Speed of motion float diameter = 0.0; void setup() { size(700, 400); background(255); smooth(); frameRate(25); //float rad = random(5.0,150.0); for (int i = 0; i < ag.length; i++) { ag[i] = new Agent(200,200,speed,angle); } } void draw() { background(255); for (int i = 0; i < ag.length; i++) { ag[i].move(); if (ag[i].nearAnotherAgent(ag[i])) { ag[i].highlight(); } ag[i].display(); } } //-------------------------------------------------------------------------- class Agent { float x,y; float diameter; float speed; float angle; color c = color(0); Agent[] nearAgent; //-------------------------------------------------------------------------- Agent(float xpos, float ypos, float sp, float dir) { x = xpos; y = ypos; diameter = random(5.0,150.0); speed = sp; angle = dir; } //-------------------------------------------------------------------------- void move() { angle += random(-0.13, 0.13); x += cos(angle) * speed; y += sin(angle) * speed; if(x >= width+diameter/2) { x = 0.0; } if(y >= height+diameter/2) { y = 0.0; } if(x <= 0.0-diameter/2) { x = width + diameter; } if(y <= 0.0-diameter/2) { y = height; } } //-------------------------------------------------------------------------- void highlight() { c = color(0,0,255); for (int i = 0; i < ag.length; i++) { if (nearAgent[i] != null) { stroke(c); line(x, y, nearAgent[i].x, nearAgent[i].y); } } } //-------------------------------------------------------------------------- void display() { stroke(c); noFill(); ellipse(x,y,diameter,diameter); c = color(0); } //-------------------------------------------------------------------------- boolean nearAnotherAgent(Agent b) { boolean near = dist(x,y,b.x,b.y) <= diameter; for (int i = 0; i < ag.length; i++) { if (near) { nearAgent[i] = b; } else { nearAgent[i] = null; } } return near; } }