1

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.

Keyvan Soleimani
  • 606
  • 2
  • 4
  • 16
Mbocpe
  • 13
  • 5
  • Where do you draw the images? The entire scene is redrawn in every frame (`draw()` is executed continuously). To make an image disappear, just don't draw it any more. – Rabbid76 Dec 26 '22 at 10:13

1 Answers1

0

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);
    }
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174