# Efficent generation of moving grating image

How to efficently generate and visualize a moving grating image with adjustable resolution?

• The distance (frequency ) of the patern has to be adjustable.

• And the whole pattern has to be moving with adjustable speed.

• Idealy the profile should be adaptable as shown under a), and b) in the figure with a square and a sinusoidal wave.

The question is a bit unspecific about the actual purpose and what the texture should look like. Where and how is it used? For example if it’s just vertical bars, generating a texture that is only one pixel high is enough. “Moving” (i guess horizontally?) can be done by simply using the texture offset in the material which will basically “scroll” the texture.

As for the actual generation of the texture, for most flexibility you could simply use an AnimationCurve. This let you specify the pattern that should be used, just like your two graphs. Though if you prefer exact results you can directly use `Mathf.Sin`

So you could simply create a texture that is 2048x1 pixel and just iterate over the pixel array and set the color based on the sampled value (either from the AnimationCurve or your preferred mathematical function) based on the x index of the pixel.

So inside a script you could simply do:

``````public AnimationCurve pattern;
public Texture2D texture;
public int resolution = 2048;
public float frequencyMultiplier = 1.0f;
public float  minValue = 0f;
public float  maxValue = 1.0f;

void Start()
{
Color[] colors = new Color[resolution];
for(int i = 0; i < resolution; i++)
{
float t = ((float)i / resolution) * frequencyMultiplier;
t = Mathf.Repeat(t, 1.0f);
float v = minValue + pattern.Evaluate(t) * (maxValue - minValue);
colors *= new Color(v, v, v, 1f);*
``````

}
texture = new Texture2D(resolution, 1);
texture.SetPixels(colors);
texture.Apply();
Note if instead you want to use Mathf.Sin you can replace `pattern.Evaluate(t)` with `Mathf.Sin(t * Mathf.PI * 2f)`.