Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make an image disappear by assigning 'undefined' to an array entry without affecting other entries?

I’m having problems making an image disappear after clicking on it by assigning ‘undefined’ to that array entry, but I don’t know how to keep rewriting the other objects while letting the draw function of p5.js extension run through the undefined entry.

function preload()
{
  images[0] = loadImage("W5 T1 p1.png");
  images[1] = loadImage("W5 T1 p2.png");
  images[2] = loadImage("W5 T1 p3.png");
  images[3] = loadImage("W5 T1 p4.png");
}

function draw() {
  ...
if (mouseIsPressed == true && carX[i] <= mouseX && mouseX <= carX[i] + 432/4 && carY[i] <= mouseY && mouseY <= carY[i] + 128/4)
        {
          images[i] = undefined;
          images.length--;
        }
}

(just don’t care too much about the other variables involved)
// by running this code, i can delete the images one by one, but they have to be in the exact order of images[3],…, images[0], any difference would cause the program to run into an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Do not decrement images.length, but test that the image is not undefined before drawing it:

function draw() {

    // [...]

    for (let i = 0; i < images.length; ++i) {
        if (images[i]) {
            image(images[i], carX[i], carY[i]);
        }
    }

    // [...]
}

Alternatively do not remove the last element from the array, but remove the selected image (see How can I remove a specific item from an array?):

function draw() {
    // [...]

    if (mouseIsPressed == true && carX[i] <= mouseX && mouseX <= carX[i] + 432/4 && carY[i] <= mouseY && mouseY <= carY[i] + 128/4) {
          images.splice(i, 1);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading