7.7: Object Communication Part 2 – p5.js Tutorial

7.7: Object Communication Part 2 – p5.js Tutorial


Hello. It is a bubble. In my previous video, which
you may not have watched, I looked at how I
could test if these two circles are overlapping. It’s not just about
the math to look at if circles are
overlapping while that’s interesting of course,
the whole point of this was really to look at an object
oriented sort of technique for how I might
write code that just checks if any bubble
intersects any other bubble. So I could say if bubble
one intersects bubble two and if I had bubble 4 and bubble
3, or bubble cat, bubble dog– so many possibilities. But what I want to
look at in this video is what if instead of
two separate variables I have an array of bubbles? Maybe there are many of them. Some of which are overlapping,
some of which are not. How do I check? How do I check if let’s say
I call this bubble bubble A. B. C. D. E. F.
G. H. I. J. K. L. I just had to go
through them all. There’s bubble A. I have to
check is bubble A intersecting BCD EFG HIJ KLM? I have to check if bubble
B is intersecting any them. How do I check if every
bubble is intersecting every other bubble? Oh! OK, let’s look at that. All right, so what
I’m going to do first is I’m just going to
change this program to have an array of bubbles. Then what I’m going to do is I’m
going to create maybe just 10 bubbles to start with. Bubbles index I
equals a new bubble. And I’m going to give
them random locations. And maybe a random size. And I’m going to have
them kind of small-ish. And then I’m going to
make those bubble objects. I’m going to comment
this out here. And I’m now going to say,
I’m going to look at– Oh, oh. I don’t know if I should
do this in this video. Well, I got to do this
in a separate video. I’m going to make a
separate video which you can go back and look at. But there is a way, a new way– This is a bad idea but I’m
going through it anyway. Right, normally I
would write this code. And I would just say bubbles
index I show bubbles I move. So let’s run this right now. I’m gonna get rid of this. Boom! So there we have
all of my bubbles showing and moving,
showing and moving. I just want to say– and I will
make another video about this specifically– that I’ve been
using this new loop that’s also part of ES6 version
of JavaScript where I could just
say four b of bubbles. b.show. B.move. So these are exactly
the same thing. I’m going to do this
in a separate video. So while you’re
here with me maybe you don’t want to
click and watch it. This is this idea that I can– I want to iterate over
every element of the array. And every element
of the array can be addressed by its
index which is typically why I might have a
counter like I to count through all the index values. 0, 1, 2, 3, 4, 5 6 7 8 9. But it’s common operation to
do something to every element of an array– and in fact, there
are lots of other ways that I’m going to show you later
that you can even do more with this– that I can just make
a variable be called– this can be anything,
cat of bubbles. The point is this is saying
for every element in bubbles put that element in this
variable and then do some stuff and then go to the next one. You can see if the same program. The reason why I don’t always
use this is sometimes I want to only look at
certain parts of the array. I need the index value. Sometime I need to move
things around in the array, delete them. But in this case,
this is going to make our life a little bit easier. So I’m going to go with it. I’m going with it. Going with it. OK, where am I? Still in this video. Now, I have all
of those bubbles. How do I know to
check if each one is intersecting every other one? Now, here’s the thing. Let’s think about this. Let’s pretend, for a
second, that there’s just one important bubble
which is a separate bubble. So I’m going to say
something like kitty. No? Puppy? Unicorn? Rainbow? Unicorn? There is a unicorn bubble. And I’m going to put it in
the center of the window and I’m actually going
to do a silly thing where I allow myself to just
control it with the mouse. Let’s make sure
this works right. Oh, and I’ve got to also– What am I doing here? Lost my mind but I’ve
got to show and move. There’s a point
to what I’m doing. It’s going to make
sense in a minute. Stay with me here. So you can see– look at this. Look at this bubble
that I’m moving around. There is one separate bubble
that’s outside of the array that I happen to be
giving the mouse location. So what if I want to check if
this bubble is intersecting any other bubble? Let’s take a look at that. So I’m going to do this. If unicorn dot intersects b. This is now saying, Hey,
I want this special bubble unicorn to check if
it’s intersecting anything in that array. Anything in that array. I just knocked this camera. OK. By the way, what’s
convenient here is I have this I already have
this function changecolor which I used in
a previous video. So I can use repurpose
that function changecolor to if it’s intersecting that
bubble to change its color. So let’s change its
color to 100 otherwise, change its color back to zero. So what I’m doing is I’m saying
if the unicorn intersects the bubble it’s got a different
brightness than if it does not intersect that
particular bubble. And look. I guess I should make that
brightness a little bit higher so you can see here. There we go. So you can see this is
working but this is different than me checking all of these
bubbles against each other. How am I going to do that? So what I need to do is I
actually don’t want anything to do with this unicorn. So let’s comment
this unicorn out. But the unicorn
served a purpose. Because it shows us right here
that this is what I want to do. For every bee in bubbles show
it move it and then check if it intersects– and really a
different way to write this that would have
made more sense is this, and what I want to do is say,
don’t check just that unicorn. Check every other b,
every other bubble. So what if I had
another loop in here? Right, there’s another loop. Just look at this for a second. For every bubble, show
it and move it then go through all the
bubbles again and check if that bubble is intersecting
any of the other Ones. It’s tricky. I feel like I need to just
pause and breathe for a second. But this is new to you. This is this idea
of a nested loop. And I feel like I want
to go over to the diagram and I want to try to redo
that diagram for a second. I think I’ve lost which
pen was the good one. Let’s try this again. I’m just going to
have four bubbles A, B, C, and D. I want to check
is A, intersecting B, C, or D? Is B intersecting A, C, or D? Is C intersecting A, B, or D? And is D intersecting
A, B, or C? Here’s the thing
though, even though this is what I want to check I
just sort of intuitively did something here. Which is what I said is
that I don’t want to check if A is intersecting A? But really what I
want to do, code wise, is I want to do this. I want to have A
check all four then B check all four then C check
off four the D check off for. But I want to make
sure I ignore when it’s checking against itself. And then, of course, we could
optimize this even further, which maybe I’ll do at
the end of this video. If A is checking B, C,
and d, B doesn’t really need to check again. But that’s only for
this particular case. There could be other
instances where we want to check A
versus B and B versus and that means
something different. So let’s come back over here
and see what I mean here. So first of all, I
want to make sure that b does not equal other. So what I want to do
is I want to check if b is intersecting
every other bubble, as long as B isn’t
checking itself. So the problem is this
actually isn’t going to work. It’s sort of going to work
but not going to work. I’ll explain to you why. The logic here is quite sound
in terms of the two loops but that change color
is a bit of a problem. So let’s run this and see. I’m not seeing
anything change color. Why not? Well, let me do something here. Let me, at least,
comment about this part. So what I want is I’m only
going to change color. I’m never going to change back. So you can see what’s
going to happen now as any two bubbles that
intersect each other– come on bubbles you can do it. There we go– they change color. But as they separate they stay. So this is an added
layer of complexity that I probably should
have anticipated when I started to making this video. And in a way I could stop here
and but since we’re doing this, I think we’ve got to
solve this problem. I’m here. You’re here. You could go on
to something else. If you want to
solve this problem, how can I now have them turn off
when they are not intersecting? So here’s the thing. What I want to do
is I can’t decide whether I want to change the
color to black or white right in here. Why is that? The reason is, let’s
consider this case where and C are overlapping. And that loop, what
it’s doing is it saying, is A intersecting A? Well, no don’t change the
color because their equal. Is A intersecting B? Well, no don’t change the
color because they’re not intersecting. Is A intersecting C? Oh, yeah. Change the color. Change the color
they’re intersecting. Change the color. OK. Oh, wait. We’re not finished yet. Is A intersecting D? No. No, they’re not. Changing back to black. Because that else doesn’t
know that the previous one was intersecting. So this is an issue right so
because I’m looping through with an else here, unless
it’s the last one I happened to check, the last one is going
to change it back to black. So what I actually need to
do is do this kind of trick– and I’m sure there’s a
more elegant way of doing this but just for
right now I can say, let overlapping equals false. So I’m going to assume it’s
not overlapping anything. I’m going to assume it’s
an overlapping anything. Then I’m going to
check all of them and if it’s overlapping at least
one, I’m going to say true. What’s funny about this is
the more it’s overlapping, I could add up a
number or something. I’m going to check if it’s
overlapping at least one set overlapping equal to true. Once I’m done checking
everything now if I do get overlapping then I can say,
b.changeColor(255) otherwise, b.changeColor(0). So this is a little bit
of a goofy piece of logic that’s associated just with
this particular scenario. But the core idea here is
that I have this nested loop. I want to check this
bubble every other bubble. OK. So let’s run this again. Let me make the bubbles– let me make more of them. Let’s make 20 of them. And you can see that
if it’s intersecting any other one it’s lighting
up, if it’s not it’s not lighting up. So this is complete. There are some things
here to change. And I’m going to just talk
them through for a second and then I’ll decide if I’m
going to implement them. So one is, is there a way– maybe it would make more
sense for me to somehow– I think it would make
more sense for me– I kind of want to
do this– for me to put this overlapping
variable inside the bubble object itself. Why can’t it keep track of that? And it could keep track
of that and based on it could just call
the show function with the appropriate– the
show function itself could set its color, potentially. So that way get rid of all this
extra gobbledygook code over here and I’m left still just
with the b.intersects(other). so that’s one thing I could do. The other thing that would
be interesting to try is to see if I could
reduce the amount of checks by just checking A versus B,
C, D. And then just B versus C, and D. c just versus D.
That’s actually all I need. And doesn’t really
matter in this case but I really should
finish this video. OK. So those are two things. One of those things
probably what I would really want to do, and need to do, is
go back to having the index. So as an exercise that
you might like to try is rewrite this code with an
I counter and a J counter. What you’ll notice is,
you can start the J with– Wait, I’ll do that. Try this. Write a lot of comments that
I should make another video to solve this and maybe I will. So that’ll be
interesting to look at. You need to go get the
counter because you can start if I is for all of
the bubbles I’m checking I can start J whatever I left off. The other thing that’s kind of
an issue here is the following. Let’s make these
bubbles really small and let’s add 200 of them. Looks like it’s working. Let’s add 2,000 of them. OK. It can not even come close. Let’s add 1,000 of them. Let’s just go back to
2,000 That was to extreme. So you can see how slow this is. Now, you might be
thinking, Oh, it’s just slow to draw 1,000 things. Which is true but let me
show you something here. What if I take out this whole
thing about intersection? It’s got no problem
animating 1,000 bubbles. The problem is in
this algorithm, if I have to check every bubble
against every other bubble, if there are three bubbles
that’s nine checks. If there are 10 bubbles
that 100 cycles, 100 checks. If there are 100
bubbles that’s 10,000. Just doing my math
there for a second. Look, this went up
by a factor of 10 but this went up
by a factor of 100. And with 1,000
bubbles suddenly I have to do one million checks. So there are ways
around this and there are algorithms for
binning, or they have fancy names and quad trees. Someday I’ll have a link
in this video description to some tutorials
where I go over how to make this
stuff more efficient. But one of the things you
really got to watch out for is this every object check
every other object is an n squared problem. As the number of
bubbles increases, the number of computation
cycles increases by the number of bubbles squared. So this is something you really
do have to watch out for. This can get quite slow and
someday Twitter’s description maybe I’ll have a link
to something which shows that more efficiently. All right I’m going to stop. I’m going to stop at
the end of this video. And if some of these
little tidbits and things are kind of interesting
and important, I will do them in
a follow up video. OK. This video is not
over, because I have noticed a pretty
fundamental mistake here worth in both of these loops
for b of bubbles where b is a variable that stands in
for every bubble in the array– just like if I’m going to
say for let i equals zero, i is less than bubbles.length. If I’m doing a loop
like this I really need to declare that
variable b otherwise, bad things could happen. So I should have let b
here and then of course, I’m doing this again
here I should say, let other bubbles there. So hopefully, you didn’t
spend too much time screaming at your viewing device while
you’re watching the video and there it is at the end here. OK. Thanks very much.

60 thoughts to “7.7: Object Communication Part 2 – p5.js Tutorial”

  1. Thank you!!
    You are my hero.
    I study nature of code everyday.
    I want to know about bin-Lattice Spatial Subdivision.(p5js)
    I beg you.

  2. Dan, I respect how much emotion you put into your explanation, because a for loop inside another for loop is definitely not something you really struggle with, but you try to convey the same emotion that the viewer might have.

    Keep up the great work!

  3. I always return when a new video is out because I love your enthusiasm and the topics. You are the perfect representation of the expression 'It's not a job it's a passion'. Keep up the great work !

  4. You're da best teacher ever dude!… btw it'll be great if u can make videos about coding and video games, how and where we use coding while making a video game, and using a good title on the video u make, for example, starcraft.

  5. Is there a reason why you're not just changing the color to black before the loop, so when it intersects it changes to white and stays white until the next time it's going trough all bubbles. Would leave out that Boolean.

  6. In your nested loops, you could have made it simpler with and iteration instead of the For – Of loop.

    for (let i = 0; i < bubbles.length-1; i++) {
    for (let j = i+1; j < bubbles.length; j++) {
    if (bubbles[i].intersects(bubbles[j]);
    // do something
    }
    }
    }
    And this way you check
    a -> b
    a -> c
    a-> d
    then
    b->c
    b->d
    lastly
    c->d

    This way you don't reverify c->a, and so on.

    EDIT : I hadn't watch the 15:00 part > < haha!

  7. If you need the index in the loop, you could do:
    For (b in bubble) {
    bubble[i].show();
    }

    Then you can minify the loop and still keep the index.

  8. Pick a type of game:
    Platformer
    RPG
    Puzzle
    Other (comment below)

    Reply with your choice.

    I’ll make it into a demo game, and upload a copy. Send me textures or link in a comment if you don’t want me finding some random Zelda sprite sheet on google.

    I’ll open source it for people trying to learn from it.

  9. I have a coding challenge for you, Daniel. I didn't know where else to post it. I hope you see this.

    Create an artificial life simulator that evolves pixels with a fitness function based on their color. Choose a target image, a Monet painting, for example. The target image represents a world map where each pixel location is a biome of a certain color. The artificial life creatures exploit these biomes for food, and those whose color is closest to the biome color are most successful.

    Begin with one pixel in the center. Every round, that pixel spawns an offspring in a random, neighboring square with a slightly mutated color. If more than one pixel occupies the same square, they fight. The pixel whose color most closely matches the pixel at that location in the target image wins, since it has the most energy. Then it spawns a child of its own. If a pixel is spawned off the edge of the map, it dies instantly. By the time every square on the map is filled with a creature, you should have a living work of art. Mutation rate is the biggest factor. Too little and the algorithm takes to long to match the target image. Too much, and it turns into a mess.

    colorDifference = function(p, t) {
    return math.abs(p.red – t.red) + math.abs(p.green – t.green) + math.abs(p.blue – t.blue);
    }

    Where p is the pixel color of the creature in question and t is the color of the pixel at that location in the target image. Obviously, creatures with a lower colorDifference are more powerful.

    Anyway, hope you find this idea interesting. I'd love to see what you do with it.

  10. What I love most about watching your videos is "You're much like me when I have new idea about making my code works". In short, we make silly noise and smiles.

  11. imo
    if(b !== other){
    if(b.intersects(other)){
    b.changeColor(255);
    } else {
    b.changeColor(0);
    }
    }
    would do the thing also instead of the overlapping variable

  12. Hi Dan,
    thank you so much for your magnetic tutorials. I say magnetic cause only watching your videos I can stick to the monitor for hours 🙂 Is there any possibility to contact you besides twitter? I would like to get your advise on a couple of ideas, which is difficult enough to describe here in comments, it's about my current student project. I would appreciate your reply. Keep up a good job man 🙂

  13. Two simple things that can be improved.
    1º > Don't check what is already checked, which you mention.
    2º > Don't keep checking if you already know your answer.

    Sure, as always it depends on what your are doing.

  14. could you solve that exercise about decreasing the number of checks using the i and j counters? I Have been stuck on it for a while and all your videos you leave it un answered D:

  15. This comment is inspired by the comments of "Kaixo Music" and "Sworn".

    This code hasn't been tested, I hope it works. Else it can be considered pseudo-code.

    for (b of bubbles) {
    b.move();
    b.show();
    b.changeColor(0);
    }
    for (let i = 0; i < bubbles.length; i++) {
    for (let j = i + 1; j < bubbles.length; j++) {
    if (bubbles[i].intersects(bubbles[j])) {
    bubbles[i].changeColor(255);
    bubbles[j].changeColor(255);
    break;
    }
    }
    }

  16. to the new foreach function you can do for(let [index, bubble] for bubbles.entries()){}
    so with the index you have also the position in the array in case you need to splice or some other stuff.

  17. Hy Dan,
    I tried to do the same example myself. I was able to achieve many things except one .. bubble turning on and Off. In your example, when you say b.intersects(other) and then you set color of intersecting bubble with b.changeColor(255). My question is how both intersecting bubbles change their color. In my case only one of the intersecting bubble changes its color.

    Another question:
    I am using for i = 0 loop syntax and this does not work same file for..of loop. My code below.

    for (let i = 0; i < bubbles.length; i++) {

    bubbles[i].show();

    bubbles[i].move();

    let overlapping = false;

    for (let j = 0; j <= i; j++) {

    if(i != j && bubbles[i].intersect(bubbles[j])){

    overlapping = true;

    }

    }

    if(overlapping) {

    bubbles[i].changeColor(255);

    } else {

    bubbles[i].changeColor(0);

    }

    }

    same code with for..of loop works. Dont understand how

    for (let b of bubbles) {

    b.show();

    b.move();

    let overlapping = false;

    for (let other of bubbles) {

    if (b != other && b.intersect(other)) {

    overlapping = true;

    }

    }

    if(overlapping) {

    b.changeColor(255);

    }

    else {

    b.changeColor(0);

    }

    }

  18. can someone help me? i always get true and false if there intersecting:

    for (b of bubble.verbuendete){
    b.move();
    b.show();

    for(other of bubble.verbuendete){
    if( b !== other && b.interact(other)){
    console.log("true")
    }else{

    console.log("false")
    }

    }}

    ————————————————————–

    this.interact = function(other){

    var d = dist(this.x, this.y, other.x , other.y)

    if(d < this.radius + other.radius) {

    return true

    }
    else{

    return false

    }
    }

    }

  19. shiffman the idea you said in this video to make the program more faster does not work……still lag is there,,,,, any more bright idea (i used selection sorting loop to implement it but no use)……i hope you will give an answer to my question?????

  20. I think it would of been easier to use regular for loops for this, then just run other for all indexes that are above the index of b, no repeats!

  21. hello dan
    I'm doing an exercise in which a circle touches a rectangle and something happens. Could you send me an example? the rectangle does not have a radius how can I do?

  22. If you delegate single objects to check if they are colliding with each others, then you have to loop one by one against any other and that lead to a n^2 complexity .

    If you instead delegate an external function to check if any two objects are colliding, then you can loop one by one each object against only the remaining unchecked objects, this is a !n complexity .

    Example:

    for (let i = 0; i < bubbles.length; i++) {
    const bubble = bubbles[i]

    for ( let j = i + 1; j < bubbles.length ; j++) {
    const other = bubbles[j]

    if ( collision(bubble, other) ) {
    bubble.changeColor(255)
    other.changeColor(255)
    }
    }

    bubble.display()
    bubble.move()
    bubble.changeColor(0)
    }

    Am I correct?
    Is it even worth?
    What's a simple way of solving this performance issue?

  23. can i code like this way?

    /*
    bubArr.forEach(function(e, i) {
    for (b of bubArr) {
    if (e !== b && e.intersets(b)) {
    e.color = "red";
    break;
    } else {
    e.color = "blue";
    }
    }
    e.move();
    e.show();
    });
    */

    is there any disadvantage to use "break;"

  24. //using foreach
    bubbles.forEach(function (b, i, bubbles) {
    b.show();
    b.move();
    let overlapping = false;
    bubbles.forEach(function (other) {
    if (b != other && b.intersects(other)) {
    overlapping = true;
    }
    if (overlapping == true) {
    b.changeColor(255);
    } else {
    b.changeColor(0);
    }
    });
    });
    }

  25. Hey Dan! @10:26 if you don't comment out the else, it still works like charm somehow. You just need to put –

    if(b !== other && b.intersects(other)) {
    other.changeColor(255);
    } else {
    b.changeColor(0);
    }

    And then the program works hasslefree!

    Nevertheless cheers to you man! I am learning a hell lot of stuff from you.

  26. hey
    i have two points
    first point
    second point
    the dist between two points = d
    i want to make array of every single possible points of d
    And i want first point to go to the second point
    Can someone help

  27. I would solve the problem of rewriting flag variable ("overlaping") by breaking out of the loop, once the condition of the if statement is true. Once the bubble overlaps, we dont have to continue running the loop, so this would have positive effect on performance aswell.

  28. That's not fair. I was able to cut the number of calls from 10 000 to on average 3 000, FPS is above 40 compared to below 30, but I still want more FPS. So where, if at all, can I find this video explaining how to make this more optimised? I wanna know T_T

  29. A solution using break:
    function draw() {
    background(0);
    for (let b of bubbles) {
    b.show();
    b.move();
    b.changeColor(0);
    for (let other of bubbles) {
    if (b !== other && b.intersects(other)) {
    b.changeColor(255);
    break;
    }
    }
    }
    }

  30. https://editor.p5js.org/MomenAl_Bakkar/sketches/eMpMhUWdZ it's WORK finally after 3 days of solving problems 🙂 I'm so happy thank you VERY much Dan <3

Leave a Reply

Your email address will not be published. Required fields are marked *