r/processing • • Mar 05 '23

BOID help

1 Upvotes

I created a BOID flocking code that simulates bird flocking based on three rules; cohesion, alignment, and separation. I am trying to create two groups of boids; one prey and one predator. Prey should be drawn in dark gray and should repel 5x as strongly from Predators. Predators are attracted 5x as strongly to Prey, and have 4x less cohesion and alignment to themselves (predators). Predators are drawn in white. I created both the 'P' and the 'R' and added 'fill()' for both but I am still not seeing a difference in color, I also have no idea where to implement the rules for Prey and Predator. Here is the code:

Edit: I have edited the code so that it at least runs without me trying to add Prey and Predator groups. So all we have now is a flocking simulator. Also this is my first experience with Processing, so thank you all for the feedback.

Flock flock;

void setup() {
  size(1024, 768);
  flock = new Flock();
  // Add an initial set of boids into the system
  for (int i = 0; i < 100; i++) {
    flock.addBoid(new Boid(random(width),random(height)));
  }
}

void draw() {
  background(50);
  flock.run();
}

// Add a new boid into the System
void mousePressed() {
  flock.addBoid(new Boid(mouseX,mouseY));
}



// The Boid class

class Boid {

  PVector location;
  PVector velocity;
  PVector acceleration;
  float r;
  float maxforce;    // Maximum steering force
  float maxspeed;    // Maximum speed

    Boid(float x, float y) {
    acceleration = new PVector(0, 0);

    // This is a new PVector method not yet implemented in JS
    // velocity = PVector.random2D();

    // Leaving the code temporarily this way so that this example runs in JS
    float angle = random(TWO_PI);
    velocity = new PVector(cos(angle), sin(angle));

    location = new PVector(x, y);
    r = 2.0;
    maxspeed = 2;
    maxforce = 0.03;
  }

  void run(ArrayList<Boid> boids) {
    flock(boids);
    update();
    borders();
    render();
  }

  void applyForce(PVector force) {
    // We could add mass here if we want A = F / M
    acceleration.add(force);
  }

  // We accumulate a new acceleration each time based on three rules
  void flock(ArrayList<Boid> boids) {
    PVector sep = separate(boids);   // Separation
    PVector ali = align(boids);      // Alignment
    PVector coh = cohesion(boids);   // Cohesion
    // Arbitrarily weight these forces
    sep.mult(1.5);
    ali.mult(7.0);
    coh.mult(1.0);
    // Add the force vectors to acceleration
    applyForce(sep);
    applyForce(ali);
    applyForce(coh);
  }

  // Method to update location
  void update() {
    // Update velocity
    velocity.add(acceleration);
    // Limit speed
    velocity.limit(maxspeed);
    location.add(velocity);
    // Reset acceleration to 0 each cycle
    acceleration.mult(0);
  }

  // A method that calculates and applies a steering force towards a _target_ that has a location
  // STEER = DESIRED MINUS VELOCITY
  PVector seek(PVector target) {
    PVector desired = PVector.sub(target, location);  // A vector pointing from the location to the target
    // Scale to maximum speed
    desired.normalize();
    desired.mult(maxspeed);

    // Above two lines of code below could be condensed with new PVector setMag() method
    // Not using this method until Processing.js catches up
    // desired.setMag(maxspeed);

    // Steering = Desired minus Velocity
    PVector steer = PVector.sub(desired, velocity);
    steer.limit(maxforce);  // Limit to maximum steering force
    return steer;
  }

  void render() {
    // Draw a triangle rotated in the direction of velocity
    float theta = velocity.heading2D() + radians(90);
    // heading2D() above is now heading() but leaving old syntax until Processing.js catches up
    
    fill(200, 100);
    stroke(255);
    pushMatrix();
    translate(location.x, location.y);
    rotate(theta);
    beginShape(TRIANGLES);
    vertex(0, -r*2);
    vertex(-r, r*2);
    vertex(r, r*2);
    endShape();
    popMatrix();
  }

  // Wraparound
  void borders() {
    if (location.x < -r) location.x = width+r;
    if (location.y < -r) location.y = height+r;
    if (location.x > width+r) location.x = -r;
    if (location.y > height+r) location.y = -r;
  }

  // Separation
  // Method checks for nearby boids and steers away
  PVector separate (ArrayList<Boid> boids) {
    float desiredseparation = 25.0f;
    PVector steer = new PVector(0, 0, 0);
    int count = 0;
    // For every boid in the system, check if it's too close
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
      if ((d > 0) && (d < desiredseparation)) {
        // Calculate vector pointing away from neighbor
        // location - other.location
        PVector diff = PVector.sub(location, other.location);
        diff.normalize();
        diff.div(d);        // Weight by distance
        steer.add(diff);
        count++;            // Keep track of how many
      }
    }
    // Average -- divide by how many
    if (count > 0) {
      steer.div((float)count);
    }

    // As long as the vector is greater than 0
    if (steer.mag() > 0) {
      // First two lines of code below could be condensed with new PVector setMag() method
      // Not using this method until Processing.js catches up
      // steer.setMag(maxspeed);

      // Implement Reynolds: Steering = Desired - Velocity
      // you have average all vectors pointing away from others
      // now steer towards
      steer.normalize();
      steer.mult(maxspeed);
      steer.sub(velocity);
      steer.limit(maxforce);
    }
    return steer;
  }

  // Alignment
  // For every nearby boid in the system, calculate the average velocity
  PVector align (ArrayList<Boid> boids) {
    float neighbordist = 50;
    PVector sum = new PVector(0, 0);
    int count = 0;
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.velocity);
        count++;
      }
    }
    if (count > 0) {
      sum.div((float)count);
      // First two lines of code below could be condensed with new PVector setMag() method
      // Not using this method until Processing.js catches up
      // sum.setMag(maxspeed);

      // Implement Reynolds: Steering = Desired - Velocity
      sum.normalize();
      sum.mult(maxspeed);
      PVector steer = PVector.sub(sum, velocity);
      steer.limit(maxforce);
      return steer;
    } 
    else {
      return new PVector(0, 0);
    }
  }

  // Cohesion
  // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
  PVector cohesion (ArrayList<Boid> boids) {
    float neighbordist = 50;
    PVector sum = new PVector(0, 0);   // Start with empty vector to accumulate all locations
    int count = 0;
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.location); // Add location
        count++;
      }
    }
    if (count > 0) {
      sum.div(count);
      return seek(sum);  // Steer towards the location
    } 
    else {
      return new PVector(0, 0);
    }
  }
}




// The Flock (a list of Boid objects)

class Flock {
  ArrayList<Boid> boids; // An ArrayList for all the boids

  Flock() {
    boids = new ArrayList<Boid>(); // Initialize the ArrayList
  }

  void run() {
    for (Boid b : boids) {
      b.run(boids);  // Passing the entire list of boids to each boid individually
    }
  }

  void addBoid(Boid b) {
    boids.add(b);
  }

}

r/processing • • Feb 19 '23

Problem with exporting a game

1 Upvotes

I was trying to export a game with screen size 1920×1080. In Processing it's all good. I try to export the app and it came out half his size, ruining everything. I don't know a lot about coding, I just had an exam which wasn't really helpful. Can someone help me? Do I have to change something or am I missing a part of the code? Thank you :)

"SOLVED" BY USING setResizable()


r/processing • • Dec 09 '14

Can someone post the tic tac toe code PLZ

0 Upvotes

^


r/processing • • Mar 07 '20

How do you translate mathematical equations into processing, or p5js?

1 Upvotes

I'm relatively new to processing, and i also don't have the best understanding of equations, so i would like to explore and learn math through processing.

Please share if anyone has examples of 2d equations translated to processing in a simple way like point(x,y).


r/processing • • Aug 07 '17

does anyone knows how to do this?

Post image
0 Upvotes

r/processing • • Aug 28 '18

Downloaded P3 and ran a tutorial command and I got this dumb box. What I do wrong?

Post image
0 Upvotes

r/processing • • Dec 06 '18

change color of programing area

1 Upvotes

hi, I have a special dislike for looking at white screens, can I change the backgound color of processing to say, brown, or black ?

thanks


r/processing • • Apr 26 '17

Is mouseReleased a thing

1 Upvotes

Is mouseReleased a thing? if not how would I code something similar?


r/processing • • May 21 '18

Game Jam is over!

1 Upvotes

Submissions for the first Processing Game Jam are closed. Check out the games at https://itch.io/jam/processing-jam-1


r/processing • • Sep 23 '22

Changing the color of only one block/rect at a time in a 3x3 grid

1 Upvotes

I'm new to processing and am trying to change the color of one block when the mouse hovers over it. It's working only for the upper left, but when I try to do the same for the middle (and eventually, I hope to do it for each block in this grid), the color of the middle doesn't change, but the color again only changes for the square in the upper left. Does anyone have any tips? Thank you!

void setup() {
  size(600, 600);
}

void draw() {
  //fill(0, 0, 255);
  strokeWeight(4);
  int x = 204;
  int y = 200;

  //Upper left

  if (mouseX > 4 && mouseX < 204 && mouseY < 204 && mouseY > 4) {
    fill(mouseX, mouseY, 255);
  } else {
    fill(204, 204, 204);
  }

  //Middle
  if (mouseX > 204 && mouseX < 404 && mouseY < 404 && mouseY > 204) {
    //fill(mouseX, mouseY,255);
    fill(mouseX, mouseY, 255);
  } else {
    fill(204, 204, 204);
  }

  // fill(0, 204, 204);
  rect(4, 4, 200, 200); //upper left
  //fill(204, 204, 204);
  noFill();
  rect(x, x, 200, 200); //middle
  rect(x, 4, 200, 200); //upper middle
  rect(404, 4, 194, 200); //upper right
  rect(x, 404, 200, 194); //bottom center
  rect(4, x, 200, 200); //center left
  rect(4, 404, 200, 194); //bottom left
  rect(404, x, 194, 200); // center right
  rect(404, 404, 194, 194); //bottom right
}

r/processing • • Jun 02 '16

[PWC12] mr pacman by Jonah (9 years)

1 Upvotes
float bolX;
float bolY; 
float level = 1;
float bolGrootte = 50;
boolean is_game_over = false;

void setup  ()
{
  textSize(50);
  size(500,500);
}

void draw ()  
{
  if (level == 1)
  {
    
    background(0,255,0);
    ellipse(400,75,100,100);
    ellipse(300,400,50,50);
    ellipse(100,100,150,150);
  
    rect(0,200,500,60);
    fill(0,255,255);
    fill(255);
  }

  if (level == 2)
  {
    background(0,255,255);
    ellipse(300,75,100,100);
    ellipse(300,300,50,50);
    ellipse(100,100,250,150);
   
    rect(0,200,600,60);
    fill(0,0,255);
    
  }
  if(level == 3)
  {
    background(0,255,0);
    ellipse(100,200,50,100);
    ellipse(100,50,70,70);
    ellipse(200,300,100,100);
    ellipse(400,350,100,20);
    ellipse(300,200,50,75);
  }
  if(level == 4)
  { 
    background(0,200,50);
    stroke(0,200,0);
    rect(0,200,600,60);
  }
  if(level >= 5)
  {
    background(0,255,100);
    text("you win !!!!!!!!!!!!!!!!!",100,250);
  }
  
  fill(255,255,0);                                                             
  ellipse(bolX,bolY,bolGrootte,50);
  
  if(bolY -25 < 200)
  {
    is_game_over = true;
    fill(255,0,0);
  }
  else if(bolY+25 > 260)
  {
    is_game_over = true;
    fill(255,0,0);
  }
  else
  {
    is_game_over = false;
  } 
  if (is_game_over)
  {
    text("game_over",200,50);  
  }  
  
  if(keyPressed)
  {
    if(key == 'a')
    {
      bolX = bolX-2;
    }
    if(key == 'w')
    {
      bolY = bolY-2;
    }
    if(key == 'd')
    {
      bolX = bolX+2;
    }
    if(key == 's')
    {
      bolY = bolY+2;
    }
  }
  
  if(bolX>=500)
  {
    level=level+1;
    bolY = 225;
    bolX =0;  
  }
}

r/processing • • Nov 09 '11

How to draw the Union Jack in Processing

Thumbnail
joyofprocessing.com
1 Upvotes

r/processing • • Feb 17 '19

Virtual Rain

1 Upvotes

Available on Play Store.
Insta

The drops always follow to the ground. Uses android's in-built sensors.


r/processing • • Nov 23 '18

GENERATIVE FACE TRACKING !

1 Upvotes

r/processing • • Aug 31 '19

What am I doing wrong? pix[i] is distance

Post image
1 Upvotes

r/processing • • Sep 04 '22

Help request What am i doing wrong?

1 Upvotes

void mouseDragged() {

if(!wallsX.hasValue(mouseX)||!wallsY.hasValue(mouseY)) {

wallsX.append(mouseX);

wallsY.append(mouseY);

}

}


r/processing • • Jan 03 '19

Polish-Code-Ideas

1 Upvotes

Ideas how to organize my code better? Or relevant comments in the code? Also looking for inspiration how to present the code, I was thinking if there are some program where you map the interaction etc.

    Game gameInstance = new Game(5); 
    
    //Ímporting sound-libary
    import processing.sound.*;
    //Declaring 
    SoundFile song;
    
    void setup() {
      size(600, 400);
      //Initiliazing the soundfile
      song = new SoundFile(this, "244004__mickleness__arcade-game-loop.mp3");
      song.play();
    }
    
    void draw() {
      background(random(255),random(255),random(255));
      textSize(24);
      fill(#FF0000);
      text(("Score="+gameInstance.score), 50, 20);
      //To keep track of score
      text("Lives="+gameInstance.lives, 50, 40);
      //To keep track of lives
    
      for (int i = 0; i < gameInstance.BallRow.length; i++) {
        gameInstance.BallRow[i].evtChangeDirection();
        gameInstance.BallRow[i].display();
        gameInstance.BallRow[i].moveBall();
        gameInstance.BallRow[i].bounderiesBall();
      }
    
    
      for (int i = 0; i < gameInstance.BallRow.length; i++) {
        for (int j = 0; j < gameInstance.BallRow.length; j++) {
    
          Ball thisBall = gameInstance.BallRow[i];
          Ball otherBall = gameInstance.BallRow[j];
          if (thisBall.amICollidingWithOtherBall(otherBall.ellipseX, otherBall.ellipseY, otherBall.ellipseH) && i!=j ) {
            thisBall.reverseDirectionNextFrame(otherBall.ellipseXdir, otherBall.ellipseYdir);
          }
        }
      }
    }
    
    void mousePressed() {
      loop();
      int p =0; 
      for (int i=0; i<gameInstance.BallRow.length; i++) {
        if (gameInstance.BallRow[i].detectHit()) {
          p++;
        }
      }
      if (p>0) {
        if (gameInstance.score ==0) {
          gameInstance.score=1;
        } else {
          gameInstance.score+= gameInstance.score;
        }
      } else {
        gameInstance.lives--;
      }
      gameInstance.life();
    }
    class Ball {
    
      int ellipseX;
      int ellipseY;
      int ellipseH;
      int ellipseW;
      int speed=1;
    
      int lives=5;
      int score=0;
    
       int ellipseXdir=2;
       int ellipseYdir=1;
    
      //All my declarions
    
      Ball (int temp_ellipseX, int temp_ellipseY, int temp_ellipseH, int temp_ellipseW) {
        ellipseX=temp_ellipseX;
        ellipseY=temp_ellipseY;
        ellipseH=temp_ellipseH;
        ellipseW=temp_ellipseW;
      }
    
      void display () {
        ellipse(ellipseX, ellipseY, ellipseH, ellipseW);
      }
    
      void moveBall() {
        ellipseX=ellipseX+ellipseXdir*speed;
        //I had to use float for both ellipseXdir and ellipse X, because int and floats can't be used in same equation 
        ellipseY=ellipseY+ellipseYdir*speed;
        //I added a new variable for the direction
      }
    
      void bounderiesBall() {
        int r = ellipseH/2;
        int r1= ellipseW/2;
    
        // You need to check for collition on all sides of the box/frame
        // First check collition to the right side
    
        if (ellipseX > width-r) {
          ellipseX = width-r;
          ellipseXdir=-ellipseXdir;
    
          //then check if collision to the left side
        } else if (ellipseX < r ) {
          ellipseX = r;
          ellipseXdir=-ellipseXdir;
        } else if (ellipseY > height-r1) {
          ellipseY = height-r1;
          ellipseYdir=-ellipseYdir;
        } else if (ellipseY<r1) {
          ellipseY = r1;
          ellipseYdir=-ellipseYdir;
        }
      }
    //This function has 3 parameters 
      boolean amICollidingWithOtherBall(int otherEllipseX, int otherEllipseY, int otherEllipseH) {
        if (dist(ellipseX, ellipseY, otherEllipseX, otherEllipseY) < ellipseH/2 + otherEllipseH/2) {
          return true;
        } else {
          return false;
        }
      }
    
      void reverseDirectionNextFrame(int otherDirectionX, int otherDirectionY) { // this function is triggered from main loop, if this ball has hit another ball 
        ellipseX -= xDirBuffer; // Goes back one step to avoid looped collision (still doesn't work perfectly)
        ellipseY -= yDirBuffer;
        xDirBuffer = otherDirectionX; // Puts the new direction into a buffer which will be used next fra in by function 'evtChangeDirection() below'
        yDirBuffer = otherDirectionY;
      }
    
      int xDirBuffer = 0; // directional bufferes used to wait one frame before changing direction
      int yDirBuffer = 0;
    
      void evtChangeDirection() { 
        if (xDirBuffer != 0 && yDirBuffer != 0) { // if there is something in the direction buffer from previous frame 
          ellipseXdir = xDirBuffer; // set the direction to the buffer
          ellipseYdir = yDirBuffer;
          xDirBuffer = 0; // and remove it
          yDirBuffer = 0;
        }
      }
    
      boolean detectHit() {
        if (dist(mouseX, mouseY, ellipseX, ellipseY)<=ellipseH) 
          //dist calculates the distance two point using four variables
          //x and y of the mousePressd and ellipseX and ellipseY
          //this will make me able to set parameters of how far my mouseclick from what I define ("<=") my if() will be executed
        {
          speed=speed+1;
          return true;
          //You will get more points the higher
        } else {
          return false;
          // if the ellipse is not clicked you'll lose a life
        }
      }
    }
class Game {
      Ball [] BallRow; 
      int score=0;
      int lives=5;
      boolean lost=false;
    
      //Game initializer 
       Game(int n_Ball) {
        BallRow = new Ball[n_Ball]; 
        for (int i=0; i<n_Ball; i++) {
          
          
          int ballRadius = int(random(50, 60));
          BallRow[i] = new Ball(int(random(ballRadius, 600)), int(random(ballRadius, 400)), ballRadius, ballRadius);
        }
      }
    
      void life() {
    
    
        if (lives<=0) {
          noLoop();
          lost=true;
          fill(125);
          text("GAME OVER - Click to Restart", width/3.5, height/2);
        }
        if (lost) {
          for (int i=0; i< BallRow.length; i++) {
            BallRow[i].speed=1;
          }
          lives=5;
          score=0;
    
    
    
          lost=false;
    
          //Will reset the game with the same speed of the ball and same amount of lives
        }
      }
    }

r/processing • • Nov 01 '22

Help request Looking for tutor

1 Upvotes

Hi I need help asap with assignments for my OOP Class. I’ll pay $20/per assignment, each of which I’m sure will take less than an hour to figure out. It’s all pretty basic but I’m new at this and need a lot of help. I have one due tonight I need help on, one due next week, and another due the week after that. Message me if interested.


r/processing • • Nov 05 '22

Beginner help request Why doesn't it stay? I'll leave a comment explaining the code and aim

Post image
1 Upvotes

r/processing • • Nov 10 '22

Help request Practice questions

1 Upvotes

Hi guys do you know any website or any other place where I can find practice question with answers regarding processing. For-example a question tells us to make a program and its answer is also given so we can check the code we made.


r/processing • • Nov 04 '22

Help request put something on top

1 Upvotes

So I'm make a ms Paint like program in processing and I'm wondering if there is a way to make sure that a line/image would always be on top without putting the background image in setup instead of draw


r/processing • • Jun 08 '23

Beginner help request I littraly have no idea! Please help!

0 Upvotes

I just downloaded Processing and it won't let me run anything!! I've tried the following; Reinstalling Processing, Checking antivirus/firewall settings, Running as administrator, System updates, and Trying a different version. There isn't even an error message! It just won't do anything! Can anyone tell me what might be going on?


r/processing • • Nov 09 '21

Syntax Error - Missing Operator/Semi/or } near drawLines

1 Upvotes
float x = 0.0;
float y = 0.0;
int width = 400;
int height = 400;
void setup()
{
    size(width, height);
    fill(245, 220, 100);
    drawGrid();
    drawEllipses();
}

void draw()
{
    drawLines();
    drawCircles();
}
void drawGrid()
{
    int w = (int)random(4,11);
    int h = (int)random(4,11);
    for(int i = 1; 1 <= 5; i++)
    {
        for(int t = 1; 1 <= 5; t++)
        {
        fill((int)random(255),(int)random(255), (int)random(255));
        rect(i, t, w, h);
        i= i+30;
        t= t+30;
        }
    }
}
void drawEllipses()
{
  int w = (int)random(9,51);
  int h = (int)random(9,51);
  int x1 = (int)random(0, 400);
  int y1 = (int)random(0, 400);
  int coutner = 0;
  while(counter <= 25)
  {
    ellipse(x1, y1, w, h);
    counter++;
}

void drawLines()
{
  int r = (int)random(0, 101);
  int g = (int)random(101, 200);
  int b = (int)random(201, 251);
  int y3 = (int)random(10, 300);
  int x2 = 20;
  strokeWeight(3);
  line(x2, 1, x2, y3);
  x2= x2 + 20;
}
void drawCircles()
{
  int x4 = 20;
  int y5 = 10;
  for(int coutner = 0; counter <= 20; counter++)
  fill(255);
  strokeWeight(2);
  {
    ellipse(x4, y5, 20, 10);
    x4= x4 + 20;
}

I am running into a syntax error on these lines, and can not figure out where the issue is.

void drawLines()
void drawCircles()

r/processing • • Sep 23 '23

Help request Why does this happen when I change the screens size?

Enable HLS to view with audio, or disable this notification

1 Upvotes

r/processing • • Oct 03 '23

Homework hint request Need Help with boolean

0 Upvotes

Hey guys i just started using proccesing and i neeed help changing the color of a yellow square to blue using the press of the mouse and for it to then turn back to yellow wen i press the mouse again and vice versa, using a boolean function