我正在P5.js项目中添加碰撞,但是我需要以某种方式跟踪哪些对象与其他对象发生碰撞,以便为它们创建各种“关系”。
我应该将对象数据放入数组中吗?我想也许每个对象都应该跟踪它自己的关系...
crossPaths(other) {
let d = dist(this.pos.x,this.pos.y,other.pos.x,other.pos.y);
d < (this.size/2 + other.size/2) ? true : false;
}
createRelationship(other) {
this.relationShip = other;
this.relationShipList.push(this.relationShip);
}
我认为这取决于您希望通过碰撞系统实现的目标。当前方法更加重视“轻松获得每个对象的碰撞”,而不是“保留所有碰撞的日志”。
这是您的方法和替代方法:
每次碰撞都被推入碰撞对象的object.relationShipList
。
object.relationShipList
。object.relationShipList
在每个对象上,并将每个冲突保存在新数组中。每个碰撞都被推入全局数组。当对象a
与对象b
碰撞时,您将注册一个window.collisionSystem.push([a, b])
。
window.collisionSystem
才能获取冲突。可以通过类似的功能来实现function getCollisionsFor(ob) { return window.collisionSystem.filter(e => { if (e[0] === ob || e[1] === ob) return true; }) }
然后像
getCollisionsFor([objectIWant])
那样调用它以获取objectIWant
对象的新碰撞数组。
window.collisionsSystem
数组。修剪数据的简便方法:只需window.collisionSystem = [];
即可清除对象。