Week 6! Objects, Arrays and More Planets!

Spacebar for fullscreen. Click to create new stars!

If you haven’t yet, please take a moment to play with the above sketch. Here is a link in the p5 editor.

This week we learned how to use objects and arrays, which is really liberating for a lot of reasons. It feels like these are the missing pieces to break out of the confines of .p5. Last week I made a space scene (click here for link). In that sketch, I created a backdrop of stars using the noise() call, which allowed me to make random points in the draw loop. I created essentially the same thing here, except this time I did it using objects and arrays. By defining the array in setup with random coordinates and varying widths, I was able to call the array in draw to make the star scene you see here. Same concept, but a lot neater in code, and a lot less “hacky.”

However, one advantage of using noise is that it does live in the Draw loop. Because of this, it was easier to scale when in full screen. In this version, when I tried to do the same thing, this is what happens:

Illustration of a space scene. All the stars are in top-left quadrant.
 

As far as I can tell, because the stars are based on random coordinates within width and height, and because that is called in the setup, the stars won’t scale when you grow the canvas. The way I fixed this was by changing the random arguments to (0, 3840) and (0, 2160) respectively (4K resolution). So, if you’re not in full screen, there’s just a bunch of canvas that you’re not seeing. The previous version didn’t have to use this workaround because everything was scaled. If I had more time, I would work that into this sketch.

In this version I used the mousePressed function to call the planet objects from an array. When you click on the canvas, a new planet appears at a random size and random color (constrained to parameters I defined). I also created a sort of coin flip based on the mousePressed that determines whether or not the planet has a ring on it. At some point I would like to be able to click and drag planets to custom sizes. Maybe for the midterm….

Another thing I couldn’t quite figure out was how to delete an object with mousePressed in spite of the fact that mousePressed is how you create an object. I have it set up right now to splice from the array to remove an object with a mouse click, but it simultaneously creates a new one in the same space. I hope to find a solution that soon as well.

Oh! I also made a version of the planet sketch using a potentiometer to zoom in and out. check it out (filmed by Nick Grant):