/*
CINDY CHI
NOV. 3, 2008
DMA 28: INTERACTIVITY
EXCERCISE K
This program utilizes a class that creates ants. Two ants crawl back
and forth on the screen, creating a visible trail of the tunnel they
are digging up while moving. At first the ants start out at regular
pace but if they meet, they react differently to each other.
The agressive ant will increase in speed and start to run around like
crazy, attacking the other ant if it gets in proximity. The passive ant
just wants to keep going on its way but if it gets too injured from
the aggressive ant its pace will slow down significantly.
*/
Ant a1;
Ant a2;
void setup()
{
size(400, 400);
smooth();
a1 = new Ant();
a2 = new Ant();
a1.assign(width/2, height/2, a2);
a2.assign(width/9, height/2, a1);
}
void draw()
{
noStroke();
fill(255, 174, 98, 15);
rect(0, 0, 400, 400);
a1.agressive();
a1.crawl();
a1.display();
a2.passive();
a2.crawl();
a2.display();
}
class Ant
{
float x = constrain(200.0, 0, 400);
float y = constrain(200.0, 0, 400);
float directionX = 1;
float speedX = .5;
float directionY = 1;
float speedY = .01;
int r = 10;
Ant other;
void assign(float startX, float startY, Ant otherAnt)
{
x = startX;
y = startY;
other = otherAnt;
}
void crawl()
{
x -= speedX * directionX;
y -= speedY * directionY + random(-.5, .5);
if(x < r || x > width - r)
{
directionX = -directionX;
}
if(y < r || y > height - r)
{
directionY = -directionY;
}
}
void agressive()
{
//if ants collide this ant runs around like mad and attacks the other
//ant if it gets within its proximity.
if(directionX == 1)
{
if((x <= other.x) && (y <= (other.y + 6)) && (y >= (other.y - 6)))
{
directionX = directionX * -1;
speedX = 2;
}
}
else //if(directionX == -1)
{
if((x >= other.x - 5) && (y <= (other.y + 5)) && (y >= (other.y - 5)))
{
directionX = -directionX;
speedX = 2;
}
}
}
void passive()
{
//if ants collide this ant tries to continue on its way but it will get
//injured if fought by the aggressive ant
if(directionX == 1)
{
if(x == other.x)
{
speedX = 0.05;
}
}
}
//draws ant
void display()
{
stroke(0);
strokeWeight(1);
fill(0);
if(directionX == 1)
{
//head, middle, butt, antennae
ellipse(x, y, 7, 7);
ellipse(x+6, y, 6, 6);
ellipse(x+12, y, 9, 9);
line(x, y, x-8, y-5);
line(x, y, x-8, y+5);
}
else
{
//head, middle, butt, antennae
ellipse(x, y, 7, 7);
ellipse(x-6, y, 6, 6);
ellipse(x-12, y, 9, 9);
line(x, y, x+8, y-5);
line(x, y, x+8, y+5);
}
}
}Cindy - K
on Wednesday, Nov 5, 2008 – 2:34 am
3 Comments
Please make the little correction needed to get rid of the black line on top and left.
I had to put the noStroke(); in draw since the ants need a stroke to draw its antennae. I hope thats okay?
Yes, that’s exactly how to do it. Thank you.