Lesson 7.5

Removing Objects from Arrays

Watch: Removing Objects from Arrays - p5.js Tutorial

Video for 7.5:

To remove an object from the canvas is to remove it from the array of which it is an element. You can remove the last item in an array with the pop() method, but to remove any element, we can use splice(i,1), where i is the ith element. The 1 indicates how many elements are to be removed from the array, which in this example is always 1.

Start with a simple sketch containing 5 balls. From the console we can see their properties apart from the radius, r, which is hidden.

We have written a function, inradius(), which checks to see if an x and y value are within the radius of the circle drawn.

We can use it within mousePressed() to call a splice method to remove a ball from the balls array. If inradius() returns true for any one ball, it removes it from the array.

We can test this by clicking on the top ball, ball[0], the red one. Note that the array now contains 4 elements, and that item 0 is now the blue ball at y = 160.

The same thing will happen if we click on the yellow ball at y = 200. The order is now blue, grey ,green corresponding to ball[0], ball[1], and ball[2].

We can continue removing balls by clicking on them.

Exercise 7.5.1