Home > Software design >  How to make an image disappear by assigning 'undefined' to an array entry without affectin
How to make an image disappear by assigning 'undefined' to an array entry without affectin

Time:12-26

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.

CodePudding user response:

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);
    }
}
  • Related