我的转换有什么问题.偏微分方程到.JS?



你好,编码社区,我需要你的帮助。我从openprocessing中获取了一个草图,我需要将其转换为p5.js。第一个脚本是源代码,下面将由我翻译。我不确定语法。

float x, y, x2, y2, rad, rad2, dist, dist2;
float deg, incr, yIn, rotateBy, ang;

void setup() {
size(600, 600);
background(#02021A);
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
void draw() {
noStroke();
fill(#02021A, 10);
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);

rotateBy += .003;
pushMatrix();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += .005;
popMatrix();
}

这就是我所做的。p5.js:

let x, y, x2, y2, rad, rad2, dist, dist2;
let deg, incr, yIn, rotateBy, ang;

function setup() {
createCanvas(600, 600);
background('#02021A');
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
function draw() {
noStroke();
fill('#02021A');
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);

rotateBy += '.003';
push();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += '.005';
pop();
}

但它仍然不起作用。你能帮我理解这两种语言的语法是否相同吗。

您差不多到了,但有几个问题:

  1. 您在顶部声明变量(例如float x, y, x2, y2, rad, rad2, dist, dist2;等(,但是您不使用值初始化它们。因为JavaScript是非类型化的(与Java不同(,解释器无法猜测您的意思是什么类型,变量将初始化为undefined(而在Java中,因为它们是float类型,所以默认为0(。对undefined进行数学运算会得到NaN(不是数字(
  2. 您不小心用字符串而不是浮点值递增了一些值:rotateBy += '.003'; yIn += '.005';
  3. 可选:fill(#02021A, 10);在p5.js中不起作用,但是您可以使用fill(r,g,b,a(并以十六进制表示法传递值:fill(0x02, 0x02, 0x1A, 10);

这是应用了以下两个修复程序的代码:

let x = 0, y = 0, x2 = 0, y2 = 0, rad = 0, rad2 = 0, dist = 0, dist2 = 0;
let deg = 0, incr = 0, yIn = 0, rotateBy = 0, ang = 0;

function setup() {
createCanvas(600, 600);
background('#02021A');
incr = 1; // numVerts = 360/incr
rad = -20;
rad2 = -160;
dist = 500;
dist2 = 550;
}
function draw() {
noStroke();
fill(0x02, 0x02, 0x1A, 10);
rect(0, 0, width, height);
fill(random(0, 255), 255, 255);
rotateBy += 0.003;
push();
translate(width/2, height/2);
rotate(rotateBy);
deg = 0;
while (deg <= 360) {
deg += incr;
ang = radians(deg);
x = cos(ang) * (rad + (dist * noise(y/100, yIn)));
y = sin(ang) * (rad + (dist * noise(x/80, yIn)));
ellipse(x, y, 1.5, 1.5);
x2 = sin(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
y2 = cos(ang) * (rad2 + (dist2 * noise(y2/20, yIn)));
ellipse(x2, y2, 1, 1);
}
yIn += 0.005;
pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

看起来很酷!玩得高兴

最新更新