我正在尝试创建一个由多个对象组成的系统,当它们相互碰撞时执行某些操作,我正在使用P5.min.js库。
我已经为网格设置了一个数组,并为对象设置了另一个数组,但是我无法弄清如何正确遍历每个网格单元并仅检查该单元格内的对象,然后再移动到下一个单元格。
以下是我目前所拥有的内容。
let molecules = [];
const numOfMolecules = 100;
let collisions = 0;
let check = 0;
let maxR = 10; //max molecule radius
let minR = 2; //min molecule radius
let numOfCol = 5;
let numOfRow = 5;
let CellW = 600/numOfCol; //gridWidth
let CellH = 600/numOfRow; //gridHeight
let remain = numOfMolecules;
let gridArray = [];
function setup() {
createCanvas(600, 600);
background(127);
for (let i = 0; i < numOfMolecules; i++) {
molecules.push(new Molecule());
}
}
function draw() {
background(127);
molecules.forEach(molecule => {
molecule.render();
molecule.checkEdges();
molecule.step();
});
drawGrid();
splitIntoGrid();
collision();
displayFR();
}
function drawGrid() {
for (i = 0; i < numOfRow+1; i++){
for (j = 0; j < numOfCol+1; j++){
noFill();
stroke(0);
rect(CellW*(j-1), CellH*(i-1), CellW, CellH);
}
}
}
function splitIntoGrid(){
for (let i = 0; i < numOfRow; i++){
for (let j = 0; j < numOfCol; j++){
tempArray = [];
molecules.forEach(molecule => {
if (molecule.position.x > (CellW*j) &&
molecule.position.x < (CellW*(j+1)) &&
molecule.position.y > (CellH*i) &&
molecule.position.y < (CellH*(i+1))) {
tempArray.push(molecule.id);
}
});
}
}
}
我是如何检测所有物体之间碰撞的:
function collision() {
for (let i=0; i < molecules.length; i++){
for (let j=0; j < molecules.length; j++){
let diff = p5.Vector.sub(molecules[j].position, molecules[i].position);
check++;
if (i != j && diff.mag() <= molecules[j].radius + molecules[i].radius){
collisions++;
molecules[j].changeColor();
}
}
}
}
据我所见,我需要将这些for循环放入另一个循环中,遍历网格中的每个单元格,但我不知道如何限制搜索对象所在的任何tempArray。 如果有意义的话,这就是我想做的事情。
function collision() {
for (let k = 0; k < gridArray.length; k++){
for (let i=0; i < gridArray.tempArray.length; i++){
for (let j=0; j < gridArray.tempArray.length; j++){
let diff = p5.Vector.sub(gridArray.tempArray[j].position, gridArray.tempArray.position);
check++;
if (i != j && diff.mag() <= gridArray.tempArray[j].radius + gridArray.tempArray[i].radius){
collisions++;
gridArray.tempArray[j].changeColor();
gridArray.tempArray[i].changeColor();
}
}
}
}
}
const diff
行之前添加一个console.log(i,j)
并告诉我控制台中记录了什么吗?这将有助于确定gridArray
是否是问题所在。打印moleculeA.position
和moleculeB.position
也会有所帮助。注意:两者都可用,因为您正在遍历gridArray
(这是一个二维数组)。 - IvangridArray [0] [0]
上。您能否注释掉两个gridArray [i] [j]
forEach
循环,并添加gridArray [i] [j] .forEach(console.log)
?像这样:function collision() { for (let i = 0; i <numOfRow; i ++) {for (let j = 0; j <numOfCol; j ++) {gridArray [i] [j] .forEach(console.log)}}}
。此外,您可能需要检查分子是否具有“position”属性。 (@Marcus) - IvansplitIntoGrid
内)。用gridArray[i][j].add(molecule)
替换gridArray[i][j].add(molecule.id)
,它应该可以正常工作! - Ivan