Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

连接第二个客户端时出现错误。我的代码通过 p5.Vector.dist() 比较两个客户端的当前位置,但出现错误,就在这里。

p5.Vector.dist(p5.js:25914)中的行是

p5.Vector.prototype.dist = function (v) {
  var d = v.copy().sub(this); //This is the exact line where the error says from
  return d.mag();
};

这是我的代码;

客户端;

//I use for loop to see all the contain of otherCircles
for(var x = 0; x < otherCircles.length; x++){
  if(otherCircles[x].id != socket.id){ //To make sure i won't compare the client's data to its own because the data of all connected client's is here
   console.log(otherCircles[x].radius); //To see if the data is not null
   if(circle.eat(otherCircles[x])){
    if(circle.radius * 0.95 >= otherCircles[x].radius){
     otherCircles.splice(x,1);
     console.log('ATE');
    } else if(circle.radius <= otherCircles[x].radius * 0.95){
     zxc = circle.radius;
     asd = zxc;
     circle.radius = null;
     console.log('EATEN');
    }
   }
  }
 }

//Here's the eat function of the circle

function Circle(positionX,positionY,radius){
//The variables of Circle()
        this.position = createVector(positionX, positionY);
 this.radius = radius;
 this.velocity = createVector(0, 0);
  
  //Here's the eat function
  this.eat = function(other) {
      var distance = p5.Vector.dist(this.position, other.position); //Heres where the error 
      if (distance < this.radius + (other.radius * 0.25)) { //Compare there distance
        return true;
      } else {
        return false;
      }
    }
}

otherCircles[]包含;

这也是行 console.log(otherCircles[x].radius);.

的输出

我认为服务器端不是必需的,因为它只是接收客户端的当前位置和大小并将其他客户端的位置和大小发送到。所有数据都存储在 otherCircles() 中。 console.log(otherCircles[x].radius); 行结果不为空,所以我知道有数据与客户位置进行比较,为什么我有一个像这样的错误。

如果没有 MCVE,将很难为您提供帮助,但我会尝试引导您完成调试。

您已经打印了 otherCircles[x].radius,这是一个好的开始。但如果我是你,我想了解更多关于 otherCircles[x] 的信息。它包含哪些变量和函数?我将从谷歌搜索 "JavaScript print function names of object" 开始,并尝试找出该对象中的确切内容。 otherCircles[x].position 的值是多少?

从那里,我还想确保定义 otherCircles[x].positionp5.Vector 的实例。它有copy()功能吗?

我可能还会使用调试器逐步调试代码 - 每个浏览器都有一个,您应该熟悉使用它。

如果您仍然无法正常工作,请 post 一个 MCVE,我们可以 运行 通过复制粘贴它。这意味着没有服务器代码,只需对您的值进行硬编码,以便我们可以看到相同的错误。我敢打赌,您在尝试将问题缩小到一个小例子时会发现您的问题。但如果没有,我们将从那里开始。祝你好运。