此 JavaScript 代码是否遵循中点位移算法?
我正在尝试使用 JavaScript 和 canvas
中点位移算法 > 按照 gamedev 上的建议。 stackexchange.com。
下面的代码生成点,其中数组索引是 x
位置,其值是 y
位置。
var createTerrain = function(chops, range) {
chops = chops || 2;
range = parseInt(range || 100);
if (chops > 8) return;
var cycle = parseInt(width / chops);
for (var i = 0; i <= width; i += cycle) {
var y = (height / 2) + getRandomNumber(-range, range);
terrain[i] = y;
}
chops *= 2;
range *= 0.5;
createTerrain(chops, range);
}
getRandomNumber()
的参数是 min
和 max
。 宽度
和高度
分别是canvas
的。
这会产生类似...
看起来很不稳定,但可能就是这样。
我这个算法对吗?如果没有,出了什么问题,你能指出我正确的方向吗?
I'm trying to use the Midpoint Displacement Algorithm using JavaScript and canvas
as recommended on gamedev.stackexchange.com.
The code below generates points where the array index is the x
position and its value is the y
position.
var createTerrain = function(chops, range) {
chops = chops || 2;
range = parseInt(range || 100);
if (chops > 8) return;
var cycle = parseInt(width / chops);
for (var i = 0; i <= width; i += cycle) {
var y = (height / 2) + getRandomNumber(-range, range);
terrain[i] = y;
}
chops *= 2;
range *= 0.5;
createTerrain(chops, range);
}
getRandomNumber()
's arguments are min
and max
. width
and height
are respective of the canvas
.
This produces something like...
It seems pretty choppy, but that may just be how it is.
Have I got this algorithm right? If not, what is wrong, and can you point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说它看起来不像中点位移,只是因为每个段都应该有一个规则的 X 轴长度(你有几乎垂直的段)。您是否尝试过生成一个简单的 4 段数组?它看起来像什么?
这是我写的一个简短的教程,您可以看到它的实际效果: Mid Javascript中的点算法
源代码:
I'd say it does not look like mid-point displacement, simply because every segment should be getting a regular X axis length (you have nearly vertical segments). Have you tried to generate a simple 4-segment array? What does it look like?
Here is a short tutorial I wrote, you can see it in action: Mid-point algorithm in Javascript
The source code:
从结果来看,您实现的算法显然是错误的。很难说你哪里出错了,因为你发布的代码不是独立的。您正在对父作用域中定义的多个变量进行操作,并且它们包含的内容或行为方式并不是立即显而易见的。
例如,
地形
是什么?首先你必须意识到,如果 y 轴上的起点和终点不匹配,你就做错了;)
The algorithm you have implemented is clearly wrong, from looking at the result. Where you went wrong is hard to say, since the code you have posted is not self contained. You are operating on several variables defined in a parent scope and it is not immediately apparent what they contain or how they behave.
What is
terrain
for example?What you have to realize first of all is, that if the start and endpoints don't match on the y-axis you have done something wrong ;)