We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I was working on a little scenery thingy with clouds moving across the screen and I added this code:
var randomCld = floor(random(0,6));
for (var ncl = 0; ncl < randomCld; ncl++) {
allClouds[ncl] = new spawnCloud(round(random(-100, innerWidth)));
}
Which starts the function:
function spawnCloud(startX) {
this.x = startX;
this.y = round(random(-400,150));
this.img;
this.randomCloud = function() {
var sel = floor(random(1,4));
if (sel == 1) {
this.img = loadImage("images/cloud_1.png");
} else if (sel == 2) {
this.img = loadImage("images/cloud_2.png");
} else if (sel == 3) {
this.img = loadImage("images/cloud_3.png");
}
}
}
And i get the error: 'Uncaught TypeError: Cannot read property 'elt' of undefined'
But when I do it like this:
setInterval(function(){
var injectCloud = new spawnCloud(round(random(-400,-600)));
allClouds.splice(0, 0, injectCloud);
allClouds[0].randomCloud();
},8000);
No error shows up??
Answers
Looks and sounds like a JS scope issue; but without knowing which line throws the error, or better still having full code to test ourselves, it's very hard to say why it's happening...
The line that the error is on is: p5.js:20418
code:
The error is an obscure JS scope issue; but I think it's likely that it's caused by your code structure rather than by a bug in p5js. The code is relatively long so it's hard to isolate the cause; but, for example, the use of loadImage in your
randomTree()
methods looks like a really bad idea and the repeated use of this structure is the most likely cause...loadImage() is a blocking file operation so should definitely not be called from inside the draw loop as you do. Instead you should load images up front (e.g. in preload/setup) and store in global variables that can then be referenced from draw...
It's also not a good idea to spawn new objects the draw loop - line #137:
That could cause some serious memory leakage... You need to keep better control over object instantiation: and where possible re-use the same objects - e.g. once something is out of bounds; don't create a new object to replace it. Instead re-position it for re-use...
Okey thank you alot! i'll keep a better eye out to how I write my code! :)