Coding Challenge 124: Flocking Simulation
VloĆŸit
- Äas pĆidĂĄn 23. 07. 2024
- In this coding challenge, I create a flocking simulation in JavaScript based on Craig Reynolds "boids" algorithm. Code: thecodingtrain.com/challenges...
đčïž p5.js Web Editor Sketch: editor.p5js.org/codingtrain/s...
đ„ Previous video: âą Coding Challenge #123:...
đ„ Next video: âą Coding Challenge 125: ...
đ„ All videos: âą Coding Challenges
References:
đ Craig Reynolds' Paper on Boids: www.red3d.com/cwr/boids/
đ Autonomous Agents - Nature of Code: natureofcode.com/book/chapter...
đ The Computational Beauty of Nature: mitpress.mit.edu/books/comput...
Videos:
đ Original Boids Simulation: âą Craig Reynolds - Origi...
âĄïž Vectors - The Nature of Code: âą 1.1 What is a Vector? ...
đȘ Autonomous Steering Agents: âą 5.1 Autonomous Steerin...
đŽ Coding Train Live 162: âą Coding Train Live 162:...
Related Coding Challenges:
đ #69 Evolutionary Steering Behaviors: âą Coding Challenge #69: ...
Timestamps:
0:00 Introduction to flocking!
2:07 What are boids?
2:33 Creating a system of boids
7:06 Discussing the flocking algorithm
7:38 Alignment!
21:48 Cohesion!
28:37 Separation!
37:00 Things to try!
Editing by Mathieu Blanchette
Animations by Jason Heglund
Music from Epidemic Sound
đ Website: thecodingtrain.com/
đŸ Share Your Creation! thecodingtrain.com/guides/pas...
đ© Suggest Topics: github.com/CodingTrain/Sugges...
đĄ GitHub: github.com/CodingTrain
đŹ Discord: thecodingtrain.com/discord
đ Membership: czcams.com/users/thecodingtrainjoin
đ Store: standard.tv/codingtrain
đïž Twitter: / thecodingtrain
đž Instagram: / the.coding.train
đ„ Coding Challenges: âą Coding Challenges
đ„ Intro to Programming: âą Start learning here!
đ p5.js: p5js.org
đ p5.js Web Editor: editor.p5js.org/
đ Processing: processing.org
đ Code of Conduct: github.com/CodingTrain/Code-o...
This description was auto-generated. If you see a problem, please open an issue: github.com/CodingTrain/thecod...
#flocking #creativecoding #autonomousagents #processing #p5js
32:00 This makes diff have length 1, not be inversely proportional to d. You have to divide by d^2. I do think the "vortex" formations you get (where boids fly through the center of the local flock, out to the side, back around, and through the center again) kinda cool, though. Also, I don't think the boids' perception range goes past the edge-wrap of the screen (that looks like a hassle to code, though).
Omg yes indeed, oops! Thank you for this correction. Pinning the comment!
"perception range goes past the edge-wrap of the screen": we can see this "bug" at 20:23 on the right of the viewport how the boids keep apearing or dissapearing, also lining up vertically on the edge.
How about if every time you had
let d = dist(this.position.x, this.position.y, other.position.x, other.position.y);
you substituted
let d = dist((this.position.x + width) % width, (this.position.y + height) % height, (other.position.x + width) % width, (other.position.y + height) % height);
That seems to work for meâŠI suspect it would help if we abstracted out the selection codeâŠis that the reFactor Song I hear playing? ;-)
Here's my current version of this sketch, I added a couple of extra little touches ;-) editor.p5js.org/NotACat/full/SkoYSoCyV
â@@PhilBoswell I don't see how that fixes the wrapping. In fact, it wouldn't change a thing at all, as
(this.position.x + width) % width == this.position.x
and same with other, and same with y and height (except possibly for a boid lying EXACTLY on the edge, I don't know enough about JS to tell). If they are on opposite sides of the screen, you'd have to SUBTRACT width or height from the one furthest to the right or furthest down (and you'd have to figure out whether it's this or other, and whether it's just x, just y, both x and y, or x for one and y for the other). That looks like a hassle to me, with mins and maxes all around, and lots of ifs flying around. Definitely put it in its own function.
@@MasterHigure I had a fit of sense and looked on StackOverflow ;-)
How about
let d = sqrt(pow(min(abs(this.position.x - other.position.x), width - abs(this.position.x - other.position.x)), 2) + pow(min(abs(this.position.y - other.position.y), height - abs(this.position.y - other.position.y)), 2))
That seems to work rather better than my feeble effort and it's not too expensive either ;-)
last video i watched, he didnt eat lunch, this video he still hasn't eaten lunch. this makes me feel he was hungry for weeks man. lol
Potatoes
@@toastyPredicament potaTOES are good
3:44 To disable autocomplete in VS Code, turn off "Accept suggestion on commit character".
This from the the creator of the THIS DOT song everyone!!!! â€đâ€đâ€đâ€đâ€đâ€đâ€
Not all heroes wear capes. Hats off dude, you are just amazing.
I have probably seen this ten times, and I find it so intriguing every time. Thanks, Dan!
This channel is GOLD! Dan is SO GOOD at explaining everything specially the most complex things.
This is such a good video, I attempted this a year ago but wasn't able to figure out all the logic on my own. I just didn't understand how 2 numbers could represent a dot moving in any direction. We only need to change the x and y values, but how you would maintain the overall speed was a mystery.
Finally, after 2 full watch throughs and a full year later I was finally able to code this just using vanilla js and html canvas. I created Vector class for the math bits, and now it actually makes sense why we would need to divide the velocity vector by its own magnitude, because it gives you a unit vector with magnitude 1 but with the same direction as before so you can scale it by whatever factor you want!!!
This was an amazing video! Thanks Dave. I enjoy having these kind of videos which are a bit longer than usual.
The editing in this video was great. Loved this one, really interesting ! You're amazing for doing all of this for free. :D
I subscribed to the channel a long time ago because of the nature of code series. This is was a really nice reminder of that topic
19:53 Dan.exe has stopped working
100 th like :D
Edit: wow someone like it :)
Hey Dan! Greetz from Denmark. Just here to say thanks. Been following your coding challenges for a while now and amazed at the great content and enticing questions you pose to your viewers (like in this video - SO many things I could think of, if only I had the time). In the phrase 'standing on the shoulders of giants' I very much consider you a (teaching) giant. Keep on choo-ing!
Thank you!
You should advertise your book more often. It took me way too many videos of yours to discover that you've written a book! A book with all you're teaching in videos! I would've gotten it way sooner, it's a really nice read so far :)!
Different mass would be fun. Few agile small boid run circles around a the heavy ones. And its also easy to implement and visualize with different radiuses/sizes.
Dan is here to introduce us and guide us through p5 and or processing. But I have to thank processing for introduce me to Dan and his videos/books. A total blast!!
Thank you so much for doing subtitles :) it really helps
Love your videos. Love the way you work towards the solution.
So cool! Some other ideas: give the birds "momentum" and have them controlled by some kind of PID controller algorithm to make them seem more natural. You could also adjust the perception radius to be anisotropic and stochastic, so simulate a bird's vision. So, they could only "see" birds right in front of them, and sometimes they wouldn't see ones to their sides and never behind them.
bird vision that flock (like pigeons) is almost 300d horizontally and 150 v
I've always wrote letters to my teachers.. always, so I can appreciate their brilliant mind helping me discover new ways to channel my genius, even if it's not so genius at times. I would just like to say, I've became an intermediate developer on many other platforms other than java due to your tutorials. I have even made realistic gears mechanics to attempt at making computer engineering into a sandbox style, so far it's going good.. and this is one of many features I am implementing into it, but beings as I have no developer team, and I'm still getting online to find tutorials for certain algoritms I've no knowledge of yet, because I'm self-taught moreorless, it'll most likely be 2025 before beta is even a thing..
This is flocking awesome. Cracking a cold one with the boids.
That was really awesome, thanks!
an easier dispersal algorithm is simply to get the CoM calculated for cohesion and move away from that point if the Boid is already too close. Make sure this force is strong enough to counter the force of attraction. but is inversely proportional to the distance. Also you can speed this up by using distance calculations that avoid square root calculations
20:20 when your adjusting the direction your allowing the oppsing vectors to cancel out. across 100 random vectors the average is close to 0. you want to change the direction to match without adjusting the length of individual vectors (unless that boid intends to speed up or slow down toward a goal).
20:25 The reason everything slows down is that the average velocity of all boids is close to zero. All the random starting velocities even out, and the average velocity of neighbours for a given boid will also be close to zero, and then we try to modify that boid's velocity towards that average
An addition to the "optimisation" discussion, rather than the inverse distance, use the inverse square. Then write an alternative distance function with just d=âxÂČ+âyÂČ to get rid of messy square roots
đ” My vector brings all the local boids to my local position!đ¶
"We're just going to start with a blank, pre-stretched canvas with a thin coat of liquid black pixels"
of liquid crystal.
He's Bob Ross but of coding
There are no bugs, only happy accidents.
I couldnt be more lucky..a video from the god of processing exactly when I was planning to do a project on flocking :) thanks....god....of processing :)
4:53 "There it is, there's by BOIIII"
One round boi
Mah BOI !!
Your teachings are very inspiring, sir. I have learned so much, and I am very thankful for what you contribute. I was thinking about the section in which there is a division by distance. As the distance approaches zero, the result will become very large, potentially causing a less smooth behavior, though maybe only for a couple of frames or so. It may be good to consider a minimum distance before any division occurs. That is my two cents, anyhow.
This is flocking awesome.
I am still in shock and awe that you feature my little "Refactor" song :) I still love your videos, and get inspired by them :)
Actually, not trying to hijack your video or anything like that, but I've have gotten a lot of emails from people wanting me to create a full length song of the "Refactor" song. I may do that, but just to put the record straight, it was only meant as a jingleish thing for you to use in a video if you wanted to. I hope you don't mind if I extend it and make it into a real song.
Yes, and then we should collaborate on a music video!!! đ”â€
@@TheCodingTrain deal!
@@TheCodingTrain you know you have to do it know, don't you
your energy never disaapoiint me
That was the best explanation I've ever heard or seen! are you planning to code challenge the pedestrian behavior soon!
I would love to see an actual game development series of him, just watching him develop a larger game.
This is so cool! Anything to do with AI is fascinating because you can control them yet you let them be free. Do more AI related videos please :D
Ive learnt VEX with your tutorials. Youre amazing.
adding this
strokeWeight(2);
line(this.position.x, this.position.y,this.position.x+this.velocity.x*3,this.position.y+this.velocity.y*3);
to the bottom of the show function let you see the direction.
also, when the flock teleports when it touch the edge, the forces are not teleported which means the flocks can split in two when half teleports and half doesn't
20:40 It slows them down because of the same reason why they make a parfect circle at the start (6:06). They each have a different direction so when they're aligning they take a average velocity so it cancels out.
37:20 just run flock() and update() in two consecutive cycles; no need to snapshot.
Hey Dan, if you need to rename a variable just select it once then press command + f2 or command + D and rename it =)
Oh, great tip!
When you're at 30 minutes in, and he says Separation is difficult, but the video ends in 12 more minutes... it's not that difficult, for Dan.
this man is fantastic
you are a gem
Awee making that without lunch Youâre crazy đ
Something else one could do is add a little bit of randomness.... Boids aren't perfect in how they follow the rules ... so maybe they vary within a range of the ideal adjustment. Also could add some background noise...maybe perlin noise which creates a 'wind' force which acts on boids based on their position...
Hey Dan,
Just wanted to sincerely thank you!
I'm still in my first year of teaching myself coding and your style of videos,
"I'm gonna show you my way and explain how it works YOU (the audience) refactor it".
Has helped me tremendously!
I made my own Javascript "WAR" card game from scratch, No tutorials!
Quick Question, at around the 19:50 mark when you copy/paste,
it automatically formats all the variables for you and changes the width to height etc..
Is that a setting? is that an extension?
I think I am just using the default "format on save" behavior in VSCode, for more: czcams.com/play/PLRqwX-V7Uu6Zu_uqEA6NqhLzKLACwU74X.html
It was not automatically changed while saving, but only postprocessed, and sped up by Dan.
He removes repeatable things in post production so it looked like it was changed with some kind of tool/linter but it wasn't :)
Ah, Craig Reynolds finally shows up in the channel.
Every time your points roll over the edge they fall out of the perception. This was most noticeable during separation and your slider testing at the end, when you have some boids cross the edge and then just yeet off on their own.
Yesss. Back to fun stuff. Lol
Flocking Awesome!
Imagine how cool a 3d flocking environment with drones would be!
Intel already did it.
cool video đ
Do simulations of whirlpools!
Hi Dan. First of all thanks for all your stuff. I've learned tons from following along. I've improved several things on my own but am kind of stumped on the state/snapshot idea. Anyone have any pointers? Much appreciated.
Hello Daniel! I am a big fan of you, and i would like to know if you have a code challenge where you explain in details the pixels and more specifally on how to do pixel measurement like px to inches.Thanks so much for insight content.
7:03 "How, how, how!" I don't get the reference. Back to Life by Soul 2 Soul?
Does someone know what the line
I donât program in JavaScript or Processing. I program in Python,C, and R. I still learn so much from these videos though.
you is good in prgramming!!!
Hey Dan, I added an avoid collisions method to avoid all the boids from gathering into the same single point, by basically reversing the cohesion method, and only checking and applying the force if any boid is within 8 of any other boid (where distance between boids is less than 8, than apply opposite force). However, I'm running into an interesting bug with the simulation. The edge of the canvas, which we've defined behavior in the edges() method teleports the boid to the other side of the canvas. It is no longer part of the flock group that it was originally in, since this teleportation overwrites it's position, and puts it out of the perception radius of the flock group it was originally in. So if a flock group gets too close to the edge, and just skims it, the edge will cut it into two groups. Those that stayed on the one side, and those that were teleported to the opposite side. Any suggestions on how to fix this?
Wow, super interesting question! The discord is a great place for this discussion! thecodingtrain.com/discord
when I do create vector with some parameter passed into it the console say that position is not a number
seems like separation should act more strongly on closer boids, not uniformly across the detection radius.
Iv'e been trying to make them rotate (made them in arrows) towards where they want to go but I don't know which vector is their direction.
the speedvektor.heading() I think is the way
One problem is the perception radius is not wrapped around the edges.
Hi Daniel... can you talk about some mechanics of how computer works? I'm totally a non-cs student, but sometimes I get confusing when a sketch become slow, why our computer can run a big program but it will get slow for our little sketch?
Boid is New York speak for bird. Have you hoid about the boid?
Wild Animal Channel 'You sing like a boid'.
This was very interesting, no matter that I understood less then 1/3 of this *programing*. Not complaining or anything. Still loved it!
How can i make the system flocking around a target?
38:40 It would be interesting if you covered how to integrate a glade GUI generator with Processing and/or with P5.js (it is available for both Java and Javascript, along with a whole different bunch of other programming languages on any platform).
I need some help if anyone can, my boids space out as expected but the more of them that join a single flock they start slowing down alot and eventually pretty much stop. When i have a fewer amount of them they work perfect but the more i add then their velocities just drop to almost nothing within a minute. Even when i do have a lot if there is a few smaller seperate flocks instead of one big one then it works but when the smaller flocks combine again the boids slow down. I have tried messing with all the values of the three rules and multiplying the forces but nothing works. If i multiply the forces tthen they will be super fast when alone or in small froups but when they combine they still slow down. Sorry for being a little repetitive if you have the time and know whats wrong please help. Thankss!
Could this happen on the Apple 2? That would be awesome!
Anyone know enough about p5 to know how to bound their movement to a path? (Like, draw a path first with mouse down, then next phase how to position them in the path? How to redraw the path that was drawn in first phase?)
Amazing! I am your biggest fan!!!
Fourier series wave coding? ;)
I like how he always says "from scratch" and then proceeds to use some game and graphics engine
@Justin batchelar agreed
This dot , this dot :) :) Nice song
Dan!!! How do you find these code challeges? I want to attempt them myself!
They get suggested here! github.com/CodingTrain/Rainbow-Topics/issues
Interesting
why in update method , we first update position, then velocity, not other way around
How about making a video on steering bhaviours with path finding?
attaboid!
Love the videos, Dan! But I'm new to all this coding stuff, and even though I follow your coding and it all seems to work (using Sublime and Firefox), I have the grey canvas and the white boid... but it doesn't move! I check over the code and it's exactly as in the video, but nothing happens... Where might I be going wrong?!
Would you mind asking at discourse.processing.org/! It's a better platform for Processing and p5.js related code questions. You can share code there easily! Feel free to link from here to your post.
@@TheCodingTrain Thank you, I'll give it a try...
How do you get the "boid" to avoid you mouse?
Hey Dan, I asked this question before, but got no answer. Why do you use VS Code now, instead of Atom? What does it offer that Atom does not? I've just gotten comfortable with Atom thanks to you, but now I'm wondering if I should be using VS Code instead!
To be honest I don't see a clear advantage of one over the other. I do see more of my students using VSCode these days so I wanted to try to learn and get used to it. I don't think you need to worry too much, both will work for all the things I do in my videos!
@@TheCodingTrain Thanks :) I was worried that maybe there was one 'killer feature' of Code I was missing out on.
Incidentally, this was one of my favourite Coding Challenges so far! Thanks for the great content.
my reason is integrated terminal in VS code.
Oh man, Boids is fun! I only know it from running simulations in Blender. Very cool to see it in 2D. Could we get this in P3D please!?
I'm hoping a viewer will implement this! (But sure I am happy to make an example.)
How about doing it on the GPU in 3D?
Whats the name of your VS code font?
@The Coding Train just to ask what editor you're using for this project (as well as all the previous ones)
Thanks in advance
This workflow series might help! czcams.com/play/PLRqwX-V7Uu6Zu_uqEA6NqhLzKLACwU74X.html
@@TheCodingTrain thanks
Your "dist()" distance function does not work at the border of the screen. x1=639, x2=1 distance should be 640-639+1=2
Indeed, this is a bug!
At 20:45 they're all slowing down because the average of an array of pseudorandomly generated vectors is about zero.
You should have let them see everyone else in the flock, but be attracted to closer ones more than ones that are farther away
That would be really slow
I created a 3d implementation with bluejays in Unity that allows you to adjust relevant values in real time. You can play it here: oxrock.itch.io/flocking-boids I also posted the scripts on github for any who are interested: github.com/oxrock/BOIDS
In my simulation the boids are incentivised to turn back when they reach the edges instead of teleporting around to the other side. This eliminates the need to monitor for boids that have already teleported but should theoretically still be in range while adding to the number of group maneuvers emerging from being constrained to a predetermined space.
Wow! This is amazing and thrilling to see! Would you mind adding a link here?
github.com/CodingTrain/website/wiki/Community-Contributions-Guide
@@TheCodingTrain Created the pull request. Glad you like it. :)
Still didn't get it what is CreateVector() ?
9:58 Why not a foreach? It's much simplier
33:56 are we really not addressing how the flock formed a crystal/lattice ????
19:54 nice
What the flock!
Hi, Iâm a graphic design student trying to expand my knowledge and these videos are an amazing help! Is there a way you can implement the accelerometer for cool interactions with moving your phone to move a 3D object for example in p5 js? That would be awesome
Yes, check out the acceleration events! p5js.org/reference/
The Coding Train i still came away a bit confused.. could you make a video about how to include the physics engine with the accelerometer? Thanks
IT would have been nice to draw them as pointed triagles though. I wonder what the logic for that looks like
You can find that code at github.com/shiffman/The-Nature-of-Code-Examples-p5.js/tree/master/chp06_agents/NOC_6_09_Flocking