# How to make space invaders destructible scenery and conform it to a shape?

We all like the bases that can be destroyed by chunks being split out,

I originally implemented it by making a rectangle filled with individual squares (2x2 pixel size CANVAS rects) that would collision detect with any bullets (On^2 very inefficient). I am now trying to make the base into a shape instead of a boring rectangle. I also want to perform collections of nearby squares when one is hit so that chunks can be taken of the base, instead of just the part that was hit. (easy to do with a rectangular array)

Is a 2 dimensianal arry still the best way to acheive this? Is there a way to create this array by somehow performing image analysis of a PNG to populate this array? Transparent parts would hold no base item at that [i][j].

• Note that it's only O(n^2) if every pixel of your base needs to collide with every other pixel. Usually though, what you want is for each bullet to ask "do I hit anything where I am currently?" which can be looked up in O(bullet count) (and you can skip bullets above/below the base area), or "did I pass through anything on my way here?" which is O(bullet count * bullet speed). Once you've detected a hit at a particular location, you can splash out to neighbouring pixels in O(hits this frame * neighbourhood radius^2) which should still be quite a bit less than O(total pixel count^2). Nov 1, 2016 at 1:30

I believe your image holds a clue as to how this could be done in a more efficient way.

Note how the damage on both of those objects results in the same pixels being destroyed.

To achieve a similar effect you could create the objects using a series of overlapping images, mapping a small collision area to each.

• ha nice spot! however I'm not striving for efficency, but the quality and "randomness" of destruction and flexibilibty of shapes Oct 20, 2016 at 17:07

You can convert a section of a canvas to an array of color values with var data = context.GetImageData(x, y, width, height). The return value is an object with the fields width, height and data. data is an array with four entries per pixel (integer values for red, green, blue and alpha).

You can scan that array, manipulate it and then write it back to the canvas with context.PutImageData(data, x, y).

Note that these methods only work when the canvas is not "tainted by cross-origin data" (contains images loaded from a different domain).

Also note that both methods require to transfer data between GPU RAM and System RAM, which is not very performance-friendly. So you should avoid doing it more often than necessary.

Checkout this post on tuts+ it shows you how to use bitmap images for this.

As in, by using the bitmap image as a mask. So you could have a bitmap image representing the arrays that are destructible. In the above tutorial there's even debris.

You could also checkout this jsfiddle