Fading Grid

This sketch uses a 2D array to hold values, and decreases changes those values to show a fading grid of cells.

This is a companion discussion topic for the original entry at https://happycoding.io/examples/p5js/arrays/fading-grid

hey super cool sketch!
I’m trying to get the grid to reset the cells periodically instead of after the mouse moves but I’m stuck :frowning:

I changed the if statement in the draw function to this so that the cells don’t reset after the user’s mouse moves:

let x = 0
let y = 0
if (x > 0 && x < width &&
y > 0 && y < height) {
const mouseR = floor(rows * (y / height));
const mouseC = floor(columns * (x / width));
cells[mouseR][mouseC] = 50;

This code removes the ability to reset cells with the mouse so the grid has a lovely fade animation once the sketch runs but the fade only happens once.

I’ve tried clearing the cells array by setting it to be empty and then refilling it with values but that didn’t work and I’ve also tried changing the frameRate after the cells have been filled but this didn’t work either sadly.

Any ideas on how I could maybe reset the cells to fill up again continuously or how to reset the cells after every x number of frames?

I’d really appreciate any help! :pray:
Merry Christmas :christmas_tree:

You can probably get rid of the if statement entirely if you don’t want the mouse to reset the animation.

Do you want to reset the whole animation for every cell, or do you want each cell to reset after a certain amount of time?

If you want to reset the whole animation, you might want to use the fameCount variable or the millis() function to take some action after a certain number of frames or milliseconds.

Here’s an example that flips an animation every 120 frames:

let falling = true;
let circleY = 100;
let framesSinceFlip = 0;

function setup() {
  createCanvas(400, 400);

function draw() {
  // Move the circle
  } else{
  // Draw the circle
  circle(width/2, circleY, 50);
  // Keep track of how long it's been since the animation flipped

  // Flip the animation every 120 frames
  if(framesSinceFlip > 120){
    falling = !falling;
    framesSinceFlip = 0;

You’d want to do something similar, where you reset the state of the grid whenever you want the animation to reset.

Alternatively, you might write a function that checks whether every cell in the grid has finished, and then use the result of that function in an if statement to reset the animation.

Another option might be to store objects in the 2D array, where the object would contain not just a value, but also the lifetime of that particular cell.

Which option you choose depends on how you think about this stuff, and what you want your animation to do. Good luck, let me know how it goes!