我正在尝试为 gdscript(Godot 引擎脚本)编写一个 perlin 噪声函数,但它似乎不起作用,我不知道我哪里出错了,无论是在排列表创建还是 perlin 噪声函数实现. 我需要一些帮助来了解出了什么问题。
我学习编写代码的地方:
http://www.dreamincode.net/forums/topic/66480-perlin-noise/ https://github.com/gustavoteixeira/tcc/tree/master/heightmap_generators
var _seed = 0
const _PI = 3.141592653589793
const MAX_COLUMN = 16
const MAX_LINE = 16
var rd_multiarray = []
var gradient = []
var permutation = []
func _ready():
#Function that uses the perlin noise () function to generate a two-
#dimensional array
#---------PSEUDO-RANDOM NUMBER GENERATOR---------------------------------
func simple_noise2d(var x, var y):
var n=int(x)+int(y)*57
n=(n<<13)^n
var nn=(n*(n*n*60493+19990303)+1376312589)&0x7fffffff
return 1.0-(float(nn/1073741824.0))
#---------INTERPOLATION--------------------------------------------------
func interpolate(var a,var b,var x):
var ft=x * 3.1415927
var f=(1.0-cos(ft))* 0.5
return a*(1.0-f)+b*f
#---------NOISE-----------------------------------------------------
func generate_permutation():
for i in range(256):
permutation.append(randf()*256)
func generateGradients():
for i in range(4):
gradient.append(0)
var point1 = Vector2()
point1.x = 1
point1.y = 0
gradient[0] = point1
var point2 = Vector2()
point2.x = 0
point2.y = 1
gradient[1] = point2
var point3 = Vector2()
point3.x = -1
point3.y = 0
gradient[2] = point3
var point4 = Vector2()
point4.x = 0
point4.y = -1
gradient[3] = point4
func dotproduct(var v1, var x2, var y2):
return float((v1.x * x2) + (v1.y * y2))
func fade(var t):
return float(t*t*t*(t*(t*6-15)+10))
func perlin_noise(var x, var y):
var x_int = int(floor(x))
var y_int = int(floor(y))
var grid_x = float(x - x_int)
var grid_y = float(y - y_int)
var x_fade = fade(grid_x)
var y_fade = fade(grid_y)
var gradient1 = gradient[ int(permutation[int(x_int + permutation[int(y_int % 256)]) % 256]) % 4]
var gradient2 = gradient[ int(permutation[int((x_int+1) + permutation[int(y_int % 256)]) % 256]) % 4]
var gradient3 = gradient[ int(permutation[int(x_int + permutation[int((y_int+1) % 256)]) % 256]) % 4]
var gradient4 = gradient[ int(permutation[int((x_int+1) + permutation[int((y_int+1) % 256)]) % 256]) % 4]
var dp1 = float(dotproduct(gradient1, grid_x, grid_y))
var dp2 = float(dotproduct(gradient2, grid_x - 1, grid_y))
var dp3 = float(dotproduct(gradient3, grid_x, grid_y - 1))
var dp4 = float(dotproduct(gradient4, grid_x - 1, grid_y - 1))
var x1lerp = float(cos_interpolate(dp1, dp2, x_fade))
var x2lerp = float(cos_interpolate(dp3, dp4, x_fade))
var final_value = float(cos_interpolate(x1lerp, x2lerp, y_fade))
return final_value
当我在另一个负责为我生成数组的函数中使用 perlin_noise () 函数时,当我将它绘制在屏幕上以更好地可视化时,我得到的东西很像白噪声,问题不在于生成世界的函数,与已经实现了 perlin 噪声功能的模块相同,并且它有效,但我的没有。