Search code examples
c#arraysunity-game-enginematrixgradient

2D Array Gradient Generation in Unity


I'm still fairly green to programming and I'm trying to write a function that generates a 2D array of custom size[x,y] and will fill it with values between 0 and 1 gradually, creating something of a square/rectangular gradient. Like this: https://i.sstatic.net/MWHrv.png

For example:

[1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.6][0.6][0.6][0.6][0.6][0.8][1.0]
[1.0][0.8][0.6][0.6][0.6][0.6][0.6][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0]

I've been trying to do it for a 16x9 array for now, but it has to be usable for 100x100+ arrays. Spent quite some time on it, but to no success, so I hope someone can help. The closest i got was

[1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][0.8][1.0]
[1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0][1.0]

And after that a lot of weird combinations.


Solution

  • the code inside the double loop should look something like

    var xValue = Math.Abs(x * 2f - xSize) / xSize
    var yValue = Math.Abs(y * 2f - ySize) / ySize
    var value = Math.Max(xValue, yValue);
    

    I.e. we compute the normalized distance to the center, going from 1 at the edge, to zero at the center. Do the same thing for both x and y-coordinates, and take the maximum. Note that this code is not optimized, you can probably move some of the computations outside the loop if this is a problem.