[英]Why am I getting NaN for integer?
这是我的代码:
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke();
}
var momentum = [0, 0]; //x and y speed
var pos = [650, 300]; //player x and y
var enemiesX = []; //enemies x's
var enemiesY = []; //enemies y's
function draw() {
background(200);
momentum[0] = (pos[0] - mouseX) / 5;
pos[0] =+ momentum;
fill(115);
ellipse(pos[0], pos[1], 30, 30);
text(pos[0] + ", " + pos[1], 20, 20);
}
我正在使用 arrays 来压缩配对的类似 x 和 y。 我正在使用文本 function 进行测试,我意识到每个数组的第一个是 NaN。 我知道它是这样的:
momentum[0] = (pos[0] - mouseX) / 5;
pos[0] =+ momentum;
但有什么问题?
此外,在人们用标记说它是重复的垃圾邮件之前,简单意味着没有其他这种性质的问题有相关的答案。
mouseX
在哪里定义? 它是undefined
,任何数字加上undefined
都将等于零。
此外, =+
与+=
不同,会导致更多问题
使用parsetInt
避免NaN
并添加对NaN
的进一步检查
createCanvas(windowWidth, windowHeight);
noStroke();
}
var momentum = [0, 0]; //x and y speed
var pos = [650, 300]; //player x and y
var enemiesX = []; //enemies x's
var enemiesY = []; //enemies y's
function draw() {
background(200);
mouseX = parseInt(mouseX);
if(mouseX === NaN){
alert('Not a number exception');
}
else{
momentum[0] = (pos[0] - mouseX) / 5;
pos[0] =+ momentum;
fill(115);
ellipse(pos[0], pos[1], 30, 30);
text(pos[0] + ", " + pos[1], 20, 20);
}
}
您的代码有两个问题。 首先是您使用=+
而不是+=
。 第二个是momentum
是一个数组,而不是一个数字。 这就是您的代码现在在您突出显示的两行中所做的事情:
(pos[0] - mouseX) / 5
momentum
数组的 0 position 中。+momentum
pos
数组的 0 position 中。 在第三个要点,发生的情况是+momentum
评估为NaN
。 然后你将该值保存在pos
数组中。 两行中的第一行很好。 我认为您想要做的是将momentum[0]
添加到pos[0]
,可以这样完成:
pos[0] += momentum[0];
the cursor, not away from it.我不确定你的意图是什么,但我的猜测是你想让圆圈 gocursor,而不是远离它。 在这种情况下,您的动量符号错误,应该是这样的:
momentum[0] = (mouseX - pos[0]) / 5;
pos[0] += momentum[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.