准确地在p5.js中检索代理的xy位置

时间:2017-01-21 21:56:05

标签: javascript p5.js

this codepen中,当代理移过网格时,我试图改变网格的单元格(称为补丁)的颜色。该示例只有两个代理(我使用笔中的Netlogo项使用var turtle)。

在绘制的每个步骤中,我尝试计算网格的每个单元格/补丁上的代理程序数量:

// this is how much to increase popularity by if an agent is on the patch
var popularityPerStep = 20; 

//I calculate the x/y position of all agents:
turtlesXpos = turtles.map(f => f.pos.x); 
turtlesYpos = turtles.map(f => f.pos.y); 

然后我使用此函数来尝试计算每个单元格/补丁上的数量,并相应地更新流行度:

function Patch(i, j) {

  this.i = i;
  this.j = j;
  this.popularity = 0; // at setup popularity is 0.
  this.totalTurtles = 0;

// countTurtles on each patch
 this.findTurtles = function() {

this.totalTurtles = 0;
for(var ii=0; ii<turtleTotal; ii++){
  if(turtlesXpos[ii] > this.i * w &&
     turtlesXpos[ii] < w + (this.i * w) &&
     turtlesYpos[ii] > this.j * h &&
     turtlesYpos[ii] < (this.j * h) + h
    )
  this.totalTurtles++;
};
}; 


// Update popularity
this.updatePopularity = function() {
this.popularity += popularityPerStep*this.totalTurtles
};


// Display patch
  this.show = function() {

  rect(this.i * w, this.j * h, w, h); // dimensions of patch

// color rectangle based on poularity
      if (this.popularity >= 1) {
        fill("gray"); //pcolor gray
      } else {
        fill("#90EE90"); //pcolor green
      }
    }; 

似乎在每个蜱上正确计算每个细胞上的药剂/龟,但是细胞的着色是关闭的。如笔中所见,它正在重新着色代理位置下方一行的单元格/补丁。这似乎应该是一个简单的数学错误,但也许我在p5.js做错了什么?

1 个答案:

答案 0 :(得分:0)

请尝试将问题缩小到MCVE。您可以在屏幕中间对单个“补丁”进行硬编码,并检查鼠标位置等。

没有MCVE,调试所有代码非常困难,但问题似乎至少部分是由这一行引起的:

if(turtlesXpos[ii] > this.i * w &&
 turtlesXpos[ii] < w + (this.i * w) &&
 turtlesYpos[ii] > this.j * h &&
 turtlesYpos[ii] < (this.j * h) + h
)

我想也许你这里有一个一个一个错误,所以我尝试从你的1变量中减去this.j(为了便于阅读,它应该真正命名为this.cellY

if(turtlesXpos[ii] > this.i * w &&
 turtlesXpos[ii] < w + (this.i * w) &&
 turtlesYpos[ii] > (this.j-1) * h &&
 turtlesYpos[ii] < ((this.j-1) * h) + h
)

我认为这会修复细胞偏移,但令我惊讶的是它实际上让它变得更糟!现在代理商下面2个空格的单元格由于某种原因而发生了变化。

所以我改为将添加 1更改为this.j变量:

if(turtlesXpos[ii] > this.i * w &&
 turtlesXpos[ii] < w + (this.i * w) &&
 turtlesYpos[ii] > (this.j+1) * h &&
 turtlesYpos[ii] < ((this.j+1) * h) + h
)

这似乎解决了你的问题。

然而,如果我是你,我不会只是拿这个代码继续卡车运输。这是代码中出现问题的症状。您需要追踪此偏移的来源并修复它。您是否可以从左下角而不是左上角绘制单元格?

如果您仍然无法理解,尝试将代码缩小到MCVE,而不是发布整个项目。