A flocking sketch using with p5.js and dat.GUI libraries
Inspired by this flocking tutorial:
http://www.flight404.com/blog/?p=459
http://libcinder.org/docs/dev/flocking_chapter1.html
var sketchContainer = "sketch";
var guiContainer = "sketch-gui";
var sketch = function (p) {
// Global variables
var fishes = [];
var jellys = [];
var whales = [];
var hammers = [];
var repulsionDist = 30;
var alignDist = 50;
var attractionDist = 150;
var huntDist = 200;
var limitDist = 300;
var maxVel = 5;
var repulsionDistSq = p.sq(repulsionDist);
var alignDistSq = p.sq(alignDist);
var attractionDistSq = p.sq(attractionDist);
var huntDistSq = p.sq(huntDist);
var limitDistSq = p.sq(limitDist);
var maxVelSq = p.sq(maxVel);
var paintLines = false;
var paintLimits = false;
var paintDetails = true;
var bgImg;
// Initial setup
p.setup = function () {
// Create the canvas
var canvas = p.createCanvas(850, 750);
// Create the water-like image to be used as the background
bgImg = createWaterImage(p.width, p.height);
// Create all the species
createFishes(300);
createJellys(100);
createWhales(1);
createHammers(3);
// Add the GUI
createGUI();
};
// Execute the sketch
p.draw = function () {
var i, fish, jelly, whale, hammer;
// Paint the water-like image
p.background(bgImg);
// Fishes
for (i = 0; i < fishes.length; i++) {
fish = fishes[i];
// Update the fish properties
fish.evaluateInteractions(fishes, true, true, true, false, false);
fish.evaluateInteractions(whales, false, false, false, true, false);
fish.evaluateInteractions(hammers, false, false, false, true, false);
fish.keepClose();
fish.update();
// Paint the fish
if (paintDetails) {
fish.paintDetail();
} else {
fish.paint();
}
// Paint the limits if necessary
if (paintLimits && i === 0) {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.