Week 8: Flock System

Inspiration:
This project aims to simulate a dynamic flocking system where agents (boids) exhibit cohesive, aligning, and separating behaviors within a visual environment. Inspired by nature and emergent patterns found in flocks of birds or schools of fish, this project integrates code with artistic composition to create an evolving narrative through visual and behavioral changes.

Description:
The project utilizes the p5.js library in JavaScript to implement a flocking simulation. Boids, represented as small circular shapes, demonstrate collective behavior influenced by separation, alignment, and cohesion. These behaviors are controlled by specific rules that affect how boids interact with their neighbors within a defined radius.

The code initializes a canvas and generates a flock consisting of individual boids. Each boid possesses properties such as position, velocity, and acceleration. Through the flock() function, boids respond to nearby neighbors within certain radii (separation, alignment, and cohesion) and adjust their behavior accordingly.

The separate(), align(), and cohere() functions within the Boid class determine how each boid interacts with others. Separation ensures that boids maintain a minimum distance from neighbors, alignment aims to match velocities with nearby boids, and cohesion encourages boids to move towards the average position of neighboring boids.

The update() function governs the boid’s movement, calculating its new position based on velocity and acceleration. The display() function visually represents each boid as a small white circle on the canvas.

The project also allows for potential narrative development or visual changes over time. For instance, altering the background or introducing new behaviors at specific frame counts could represent the evolving story or tension and release dynamics within the simulation.

// Flocking behaviors (separation, alignment, cohesion)
flock(others) {
let separationForce = this.separate(others);
let alignmentForce = this.align(others);
let cohesionForce = this.cohere(others);

separationForce.mult(1.5);
alignmentForce.mult(1.0);
cohesionForce.mult(1.0);

this.acceleration.add(separationForce);
this.acceleration.add(alignmentForce);
this.acceleration.add(cohesionForce);
}

Assignment Week #8 – Predator Prey Simulation

Predator-Prey simulation

For this assignment, I wanted to recreate an underwater chase scene. My goal was to show simulation through autonomous agents, like a single predatory shark chasing a school of fish. The fish reacts to the shark’s actions by fleeing. Each agent has its own set of rules and behaviors that it follows in their 2D ocean.

Implementation:

  • The Shark’s Path: To control the shark’s movement, I used a Perlin noise algorithm. This created a smooth, random path that mimics how unpredictable a real shark’s patrol through the water is.
  • Fish Fleeing:  In this state, their behavior changes dramatically. They prioritize moving away from the shark over any other actions they might be taking, such as wandering 
  • Boundary Constraints: I coded the fish to wrap around the edges of the canvas so they stay in the canvas
  • Shark Movement: Instead of being directly controlled, the shark follows a path made by perlin noise. I’ve tuned this function to keep the shark from moving randomly and give its hunt a bit of randomness. Also, the shark slows down when it gets closer to its target.

Sketch:

Code: 

The following is the function for sharks seeking their target which is calculated by Perlin noise.

class Shark {
  
  seek(target) {
    let desired = p5.Vector.sub(target, this.position);
    let distance = desired.mag();
    desired.normalize();
    if (distance < 100) {
      let m = map(distance, 0, 100, 0, this.maxSpeed);
      desired.mult(m); // Slow down as it gets closer to the target
    } else {
      desired.mult(this.maxSpeed);
    }
    let steer = p5.Vector.sub(desired, this.velocity);
    steer.limit(this.maxForce);
    this.applyForce(steer);
  }
  
}
  • The seek method in the Shark class steers the shark towards a target.
  • It calculates the direction to the target and if the shark is within 100 pixels, it slows down proportionally to the distance to avoid overshooting.
  • The map function adjusts the shark’s speed dynamically, allowing for a gradual stop as it reaches the target.
  • This prevents the shark from ‘spazzing’ or jittering when it gets close to where it wants to go.

The following is the function for fish fleeing the shark

class Fish {  
  flee(predator) {
    let desired = p5.Vector.sub(this.position, predator.position);
    let d = desired.mag();
    if (d < 100) { // If the shark is within 100 pixels
      desired.setMag(this.maxSpeed); // Set maximum speed
      let steer = p5.Vector.sub(desired, this.velocity);
      steer.limit(this.maxForce); // Limit the force to be applied
      this.applyForce(steer);
    }
  }
  
}
  • The flee function in the Fish class calculates the escape direction from the shark.
  • If the shark is within a certain range, the fish accelerates to its top speed away from the shark.
  • This quick response mimics a fish’s instinct to escape predators.

Challenges: 

  • Precision in Shark Movement: Improving the shark’s movement to stop it from “spazzing” as it gets to its target was a difficult job that required slowing the velocity as it got closer to the target.
  • Fish Behavior Realism: Making flocking behavior was hard to implement because you had to find a fine balance between random movement and organized group dynamics. After a shark chase, there were difficulties getting the fish to gather back into a proper formation. I think this aspect still needs some work to make it more realistic.

Future Improvements: 

  • User Interaction Features: I want to look into ways for users to connect more directly with the simulation, such as using different inputs to change the path of the shark or the fish.
  • Ecosystem Development: I like the idea of adding more species and environmental features, like currents or obstacles, to make the experience more interesting.
  • Develop Flocking Behavior: To make the fish’s reaction seem real, the flocking and evasion algorithms have to be tweaked to match how fish move naturally.

Assignment 8: Snickers and Mouths

Inspiration:

Inspired by the playful movements of animals in nature and classic video games, this project aims to bring a sense of whimsy and curiosity to the canvas. It draws from the idea of contrasting behaviors in a dynamic and visually engaging way.

Concept:

The project features a canvas where Snickers and Mouths, represented as animated elements, interact with distinct steering behaviors.

  • Snickers: These elements wander aimlessly around the canvas, moving in a random and carefree manner, much like the unpredictable paths of creatures in the natural world.
  • Mouths: Mouths, on the other hand, are purposeful seekers. They are drawn to the Snickers and move strategically to follow them, akin to the way predators seek their prey.

This simple concept focuses on the contrast between wandering and seeking behaviors, creating a visually captivating and contemplative experience for viewers.

Program

 

Code assignment – week 8 – Bug Spray

In this sketch, I created an interactive simulation where a bug spray chases a cockroach on the screen. The bug spray employs steering behaviors to follow the cockroach, and when the cockroach is within a close proximity, the bug spray visually simulates spraying.

Challenge

One challenge encountered was ensuring smooth steering behavior for the bug spray. Tweaking parameters such as maximum speed, maximum force, and the radius for arrival behavior required careful adjustment to achieve a natural-looking pursuit.

Code Snippet

push();
    translate(this.pos.x, this.pos.y);
    rotate(this.vel.heading());
    noStroke();
    fill(0, 200, 0); // Color for bug spray
    rect(-8, -25, 16, 50); // Bug spray shape
    fill('yellow'); // Color for bug spray nozzle
    ellipse(0, -25, 16, 16); // Bug spray nozzle
    pop();

As seen in the above code, I used push and pop to make it simpler in creating the shapes for the code. I also used the rotate function to make the orientation of the bug spray to correspond to to the cockroach position.

Future Improvements

  1. Particle System: Enhance the spraying effect by adding a particle system to visually represent the spray dispersing.
  2. Obstacle Avoidance: Implement obstacle avoidance behaviors to make the bug spray navigate around obstacles on the canvas.

Coding Assignment Week #8 – Fleeing Butterflies

Inspiration :

In nature, there are several organisms and species that naturally are attracted to certain scents or colors in other organisms such as plants and animals. And on the contrary, they also flee from certain things. In more scientific terms, this process is also called, escape response.  It is a mechanism by which animals avoid potential predation.

Birds of a feather flock together to confuse potential predators

 

Concept: 

This program works with a butterfly class, that we instantiate several of and add a fleeing method to it. The class has properties such as position, velocity, acceleration, maximum speed, maximum force, radius, and wing color. The class includes methods for updating the butterfly’s position based on its velocity and acceleration, applying external forces to the butterfly, making the butterfly flee from a specified target (the ellipse in position mouseX MouseY)  if it is within a certain distance, and displaying the butterfly on a canvas using a shape resembling butterfly wings. The butterfly’s appearance is determined by random colors and the shape of its wings is drawn using ellipses.

33 Butterflies aesthetic ideas | butterfly, aesthetic, beautiful butterflies

Program:

 

https://editor.p5js.org/ea2749/sketches/d3LJADOUE