- Home /

# Simple Voronoi Code not working

I tried to convert a fast voronoi code on this page, I tried so many different combinations of code and there is always the same error, can anyone see what is wrong with my code? it looks like the loop is generating different values for adjacent tiles. its supposed to cycle through 3x3 sets of tiles.

here's original code:

```
float voronoi( in vec2 x )
{
ivec2 p = floor( x );
vec2 f = fract( x );
float res = 8.0;
for( int j=-1; j<=1; j++ )
for( int i=-1; i<=1; i++ )
{
ivec2 b = ivec2( i, j );
vec2 r = vec2( b ) - f + random2f( p + b );
float d = dot( r, r );
res = min( res, d );
}
return sqrt( res );
}
```

and unity version that doesnt work:

```
function rndng ( n: float ): float
{//random number -1, 1
var e = ( n *321.9)%1;
return (e*e*111.0)%2-1;
}
function voronoi( vtx: Vector3 )
{
var px = Mathf.Floor( vtx.x );
var pz = Mathf.Floor( vtx.z );
var fx = Mathf.Abs(vtx.x%1);
var fz = Mathf.Abs(vtx.z%1);
var res = 8.0;
for( var j=-1; j<=1; j++ )
for( var i=-1; i<=1; i++ )
{
var rx = i - fx + rndng(px*pz + i );
var rz = j - fz + rndng(px*pz + j );
var d = Vector2.Dot(Vector2(rx,rz),Vector2(rx,rz));
res = Mathf.Min( res, d );
}
return Mathf.Sqrt( res );
}
```

here is shadertoy version

**Answer** by frogsbo
·
Feb 13, 2014 at 02:53 PM

argz.

this line was wrong.

```
var rx = i - fx + nz2d(px+i ,pz + j ) ;
var rz = j - fz + nz2d(px+i ,pz + j ) ;
```

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Need some shader code translating to ShaderLab. Random float generation. 0 Answers

Change vertex height with noise texture through shader 0 Answers

Carpet in Shadergraph? 0 Answers

Noise node column to "texture" in shader graph? 0 Answers

How can I get more realistic using waves with a surface shader? 0 Answers