We are about to switch to a new forum software. Until then we have removed the registration on this forum.
hello guys im new here and i learn some of p5 programming and i have a problem with some function i wrote this program but i have a error on line 38
var d = dist(v1.x, v1.y ,v2.x, v2.y); i got a error message cannot read property 'x' of undifined
var bubles=[];
var reached = [];
var unreached=[];
function setup() {
createCanvas(410,410);
}
function mousePressed(){
var v = createVector(mouseX,mouseY);
ellipse(v.x,v.y,20,20);
bubles.push(v);
}
function draw() {
background(200,200,200);
for(var i=0;i<bubles.length;i++){
unreached.push(bubles[i]);
}
reached.push(unreached[0]);
unreached.splice(0,1);
while(unreached.length>0){
var min=1000;
var rIndex;
var uIndex;
for(var i=0; i<reached.length;i++){
for(var j=0; j<unreached.length;j++){
var v1 = reached[i];
var v2 = unreached[j];
var d = dist(v1.x, v1.y ,v2.x, v2.y);
if(d<min){
min=d;
rIndex=i;
uIndex=j;
}
}
}
line(reached[rIndex].x,reached[rIndex].y,unreached[uIndex].x,unreached[uIndex].y);
reached.push(unreached[uIndex]);
unreached.splice(0,uIndex);
}
}
Answers
Please edit your post and format your code. Select your code and press ctrl+o and have an empty line above and below your code.
Kf
reached.push(unreached[0]);
. :(|)unreached[0]
contains a p5.Vector object, even though it is possible to beundefined
there as well. :>As a workaround, check whether unreached[] got any length before deciding to push() the head element index
0
to reached[]:unreached.length && reached.push(unreached[0]);
Of course there still might be other bugs lurking there. But for now it's all I can think of. :-\"
You should also consider simplifying your algorithm. Is it really necessary to have 2 extra arrays as helpers for the main 1? /:)
ok thanks brother for yuor advice but i think the problem in the propérite x how can i read the properite of the vector v1 ?
You're already accessing it correctly. As long it's a p5.Vector reference, there are 3 properties: x, y & z:
http://p5js.org/reference/#/p5.Vector