I'm creating a function in Unity to fill a texture with a gradient allowing for directions horizontal, vertical, diagonal, and radial. The first three were easy enough, and work with rectangular images, however, the only algorithms I could find for a radial gradient depend on square images, like below:
Vector2 center = new Vector2 ( texture.width * 0.5f, texture.height * 0.5f );
for ( int y = 0; y < texture.height; y++ )
{
for ( int x = 0; x < texture.width; x++ )
{
float distanceFromCenter = Vector2.Distance ( center, new Vector2 ( x, y ) );
float t = invert ? 1 - ( 0.5f - ( distanceFromCenter / texture.width ) ) : 0.5f - ( distanceFromCenter / texture.width );
texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
}
}
How do I make it work on rectangular images?
The issue is with the division of texture.width. With a square texture, this does not matter as both it's height and width are the same length.
You need to divide the current point by the texture's dimensions. This will give you x and y values between 0 and 1.
Vector2 relativePoint = new Vector2 ( x / texture.width, y / texture.height );
Next, get the distance between the new center point (0.5, 0.5) and this new point, giving you the centered sampling value at the point (x, y).
float centeredPointSampleValue = 0.5f - Vector2.Distance ( new Vector2(0.5, 0.5), relativePoint );
And put it all together:
for ( int y = 0; y < texture.height; y++ )
{
for ( int x = 0; x < texture.width; x++ )
{
Vector2 relativePoint = new Vector2 ( x / texture.width, y / texture.height );
float centeredPointSampleValue = 0.5f - Vector2.Distance ( new Vector2( 0.5, 0.5 ), relativePoint );
float t = invert ? 1 - centeredPointSampleValue : centeredPointSampleValue ;
texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
}
}