我似乎遇到了在数组中嵌套矢量的问题。我使用了createVector(),但发现它不起作用。我查看了其他文章,虽然它们适用于非p5 javascript,这就是我目前所处的位置:
function makePoints() {
var cities = [];
if (difficulty === 'hard') {
cities.length = 40;
for (i = 0; i < cities.length + 1; i++) {
cities.push(new createVector(random(20, width - 20), random(20, height - 20)));
}
}
}
答案 0 :(得分:0)
为什么要更改cities.length
? Wy不仅仅是:
var difficulty = 'hard';
function setup() {
createCanvas(720, 400);
makePoints();
}
function makePoints() {
var cities = [],
citiesSize = 40;
if (difficulty === 'hard') {
for (i = 0; i < citiesSize; i++) {
cities.push(createVector(random(20, width - 20), random(20, height - 20)));
}
}
console.log(cities);
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.min.js"></script>
&#13;
答案 1 :(得分:0)
您首先说cities.length = 40
用40 undefined
填充数组。然后你正在推动它,但使用你推动的阵列作为停止的长度。因此,第一次推动使长度为41,第二次推动使长度为42.您将遇到无限循环,因为i
永远不会达到cities.length + 1
(应该只是cities.length
)。
如果你想让你的阵列长40,那么不要推动这样做:
for (i = 0; i < cities.length; i++) {
cities[i] = createVector(random(20, width - 20), random(20, height - 20));
}