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



在这个代码笔中,当代理在网格上移动时,我试图更改网格的单元格(称为补丁)的颜色。这个例子只有两个代理(我在笔中使用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中做错了什么?

请尝试将您的问题缩小到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
)

我想您可能在这里有一个错误,所以我尝试从this.j变量中减去1(为了可读性,应该将其命名为类似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,而不是发布您的整个项目。

最新更新