This program creates a Flyer
class to encapsulate all of the logic for creating a “bug” that follows the mouse around using a heading angle and a speed. This provides more realistic movement, but it lets us keep our draw()
function nice and simple.
Flyer[] flyers = new Flyer[5];
void setup(){
size(200, 200);
for(int i = 0; i < flyers.length; i++){
flyers[i] = new Flyer();
}
}
void draw(){
background(200);
for(int i = 0; i < flyers.length; i++){
flyers[i].step();
flyers[i].draw();
}
}
class Flyer{
float x = random(width);
float y = random(height);
float heading = random(TWO_PI);
float speed = random(1, 3);
float radius = random(5, 20);
void step(){
float angleToMouse = atan2(mouseY-y, mouseX-x);
//prevent case where heading is 350 and angleToMouse is 10
if(heading-angleToMouse > PI){
angleToMouse += TWO_PI;
}
else if(angleToMouse-heading > PI){
angleToMouse -= TWO_PI;
}
//turn towards mouse
if(heading < angleToMouse){
heading+=PI/50;
}
else{
heading-=PI/50;
}
//move in direction
x += cos(heading)*speed;
y += sin(heading)*speed;
//wrap around edges
if(x < 0){
x = width;
}
if(x > width){
x = 0;
}
if(y < 0){
y = height;
}
if(y > height){
y = 0;
}
}
void draw(){
ellipse(x, y, radius, radius);
}
}
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
If this seems complicated, think about it this way: when using a class, we only need to worry about the behavior of a single Flyer
instance (in other words, we only need to know how a single “bug” behaves). Then when we get that single Flyer
working, we can use an array or an ArrayList
to add as many Flyer
instances as we want!
Flyer
a random color.background()
to the setup()
function to show trails.This example creates a swarm that follows your mouse around.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!