cannot read property 'x' of undifined

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

    • The algorithm above is too complex to properly understand! =;
    • Seems some kinda enqueue/dequeue (FiFo) of p5.Vector objects for array bubles[], but w/ the aid of 2 other arrays: reached[] & unreached[].
    • Hard to pinpoint where the problem is though. #-o
    • My best bet'd be @ line #21: reached.push(unreached[0]);. :(|)
    • B/c it is assumed unreached[0] contains a p5.Vector object, even though it is possible to be undefined there as well. :>
  • edited February 2017

    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 ?

  • edited February 2017

    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

Sign In or Register to comment.