Animation with variables

In our second week of ICM, we were introduced to the power of variables and transformations. We were tasked to use variables to animate a sketch with the following requirements:

  • One element controlled by the mouse.
  • One element that changes over time, independently of the mouse.
  • One element that is different every time you run the sketch.

Although we were allowed to create a new sketch altogether, I thought it’d be fun to animate my space scene from last week.

I first focused on what elements could change each time I ran the sketch. I decided to randomize the colors of the planet (no need to be so terra-centric) and the location of the moon. I also randomized the size of the stars and their fill in order to make it look like the stars were glowing.

Next, I thought about what element I could change over time. I decided to animate my shooting stars to move across the sky when the sketch launches. I couldn’t figure out how to start my shooting star on the right side and move left, so I coded my stars to start on the left and move right through space.

Lastly, I decided to control the UFO with the mouse. To make the assignment a little more fun, I referenced the Image function in p5.js to call an image of an explosion whenever the UFO intersected the planet. Adding this element to the sketch helped me practice the dist function.

The sketch above shows how far I got in my space scene before I ran into problems. I couldn’t figure out how to get the explosion to stay where the UFO first intersected the planet. As you see above, the explosion continues to follow mouseX and mouseY.

I went to get help from Justin Peake, and we decided to add a exploded boolean in order to track when the UFO intersected the planet. We had a bit of trouble with the logic to track the x,y coordinates of when the intersection happened, but we eventually solved it by nesting a conditional within a conditional.

Once we figured out how to keep the explosion stationary, I added a mouseClick() function in order to switch the exploded boolean back to reset the sketch.

You can see the code here: