我正在用 C# 编写 Perlin Noise 的实现。 当我运行程序时,它会输出:
每个细胞单独看起来都不错,但与它的邻居相比,它们不匹配。 (在极少数情况下,两个或多个单元格确实相互匹配)。
这是用于所有计算的 Perlin 结构:
public struct Perlin
{
public struct _2D
{
public static float Simple(float x, float y, int seed)
{
Vector2 pos = new Vector2(x % 1, y % 1); // Position in the unit square
Vector2[] points = new Vector2[4];
points[0] = new Vector2(Mathf.Floor(x), Mathf.Floor(y)); // Corner positions
points[1] = new Vector2(Mathf.Floor(x), Mathf.Ceil(y)); // Corner positions
points[2] = new Vector2(Mathf.Ceil(x), Mathf.Ceil(y)); // Corner positions
points[3] = new Vector2(Mathf.Ceil(x), Mathf.Floor(y)); // Corner positions
Vector2[] vectorTable = new Vector2[] { new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1) , new Vector2(Mathf.Sqrt(2), 0), new Vector2(0, Mathf.Sqrt(2)), new Vector2(-Mathf.Sqrt(2), 0), new Vector2(0, -Mathf.Sqrt(2)) };
Vector2[] gradients = new Vector2[4];
for (int g = 0; g < gradients.Length; g++)
{
gradients[g] = vectorTable[Mathf.RoundToInt(Random(new Vector2(points[g].x + seed, points[g].y + seed)) * (vectorTable.Length-1))]; // Gradient vector
}
Vector2[] directions = new Vector2[4];
for (int d = 0; d < directions.Length; d++)
{
directions[d] = (new Vector2(x - points[d].x, y - points[d].y) - pos).normalized; // Direction vector from the x and y position to the corner
}
float[] dots = new float[4];
for (int i = 0; i < points.Length; i++)
{
dots[i] = (Vector2.Dot(directions[i], gradients[i])); // Dot products
}
float lerp1 = (Mathf.Lerp(dots[0], dots[1], Fade(pos.y)));
float lerp2 = (Mathf.Lerp(dots[2], dots[3], Fade(pos.y)));
float lerp3 = (Mathf.Lerp(lerp1, lerp2, Fade(pos.x)));
return (lerp3 + 1) / 2; // Remapping the output from (-1 to 1) to (0 to 1)
float Fade(float t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
}
}
}
这是 Random() 函数:
static float Random(Vector2 seed)
{
Vector2 v1 = new Vector2(3.1251f, 17.8737f);
float f1 = 43758.545312f;
return fract(Mathf.Sin(Vector2.Dot(seed, v1) * f1)) ;
float fract(float x)
{
return Mathf.Abs(x % 1.0f);
}
}
我试图反转某些单元格中的颜色,但它也没有产生预期的结果。