How do I get better performances on pixel detection (Canvas)

0 favourites
  • 4 posts
From the Asset Store
Vintage steam pixels for your UI! 125 unique assets in a single pack!
  • Hi.

    I'm working on a game similar to worms.

    I'm trying to use the Canvas plugin to destroy the landscape pixel per pixel.

    I've also set up some events to create more or less particles, regarding the proportion of destroyed landscape.

    You can check it up here : http://canapin.com/construct/worms/terrain

    Basically, it checks every X pixels in the square containing the round hole created on each click.

    You can increases X to get lower precision and better performances.

    The main issue here is that checking every single pixel of a square is VERY slow. Why ?

    The computer freezes for about a second when I check for every pixel.

    It stills freezes for a short time even if I checks every 4 pixels. That's acceptable for a turn bases game thought, but not that nice.

    Is there any other way to do the same thing with better performances ?

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • This post may help.

    Sampling pixels is a relatively slow operation that adds up when doing it multiple times. In javascript you can copy a whole pixel area to an array. The result is very fast sampling of any of those values. The expression in the canvas object is .AsJSON and it returns a json string that then can be loaded in the Array object.

    I added it as an experiment so it isn't very user friendly. For one the array size is [1, 1, width*height*4] and to access a particular pixel you have to do it with [0, 0, (width*y+x)*4+i] where i is 0 for red, 1 for green, 2 for blue, and 3 for alpha. Also all the pixel data is in the range of 0-255.

    With regard to performance, one rgbaAt() is faster than one .AsJSON, but .ASJSON becomes faster when you want to sample many pixels. Also the bigger the canvas the slower it is, so when you only need to check a smaller area you should paste the canvas to a smaller one and use .ASJSON on that.

    Also alternatively Another idea is to just copy the terrain to an array to read from and clear it manually when you clear parts of the canvas. Tedious, yes but gives good performance.

  • Thank you for the explanation.

    I'll look at this

  • Hi again.

    I've used an array as you said to read pixel informations. It's much faster !

    Now i just have to update the array, replacing all pixels from the hole by transparent pixels (a few thousand).

    Hope this won't be too CPU expensive.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)