1

I am adding collisions in a P5.js project, but I need to somehow track which objects have collided with others so I can create various "relationships" for them.

Should I just put the object data into an array? I thought maybe each object should track it's own relationships...

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);
}
matski
  • 541
  • 6
  • 19

1 Answers1

1

I think it depends on what you want to achieve with the collision system. The current approach gives more importance to "easily get collisions per object" rather than "keep a log of all collisions".

Here is your approach and an alternative:

Your approach:

Every collision is pushed into object.relationShipList of the colliding object.

  • Easy and fast way to fetch all collisions per object: Only read object.relationShipList.
  • Very hard way to get a log of all collisions: Getting a log of all collisions would require calling object.relationShipList on every object and saving each collision in a new array.
  • Will lead to data duplication: If there are multiple objects colliding, each object will generate its own collision.

Alternative that I would chose:

Every collision is pushed into a global array. When object a collides with object b, you register a window.collisionSystem.push([a, b]).

  • A little bit more complex way to get collisions per object: You would need to query window.collisionSystem to get collisions. This can be achieved with a function like
function getCollisionsFor(ob) {
  return window.collisionSystem.filter(e => {
    if (e[0] === ob || e[1] === ob) return true;
  })
}

And then call it like getCollisionsFor([objectIWant]) to get a new array of collisions for the objectIWant object.

  • Easy way to keep track of all collisions without duplicate data: This is -of course- the window.collisionsSystem array.
  • Easy way to prune data: Just window.collisionSystem = []; to clear up the object.

Recommended reading about this particular question in Game Engines, see: https://books.google.com/books?id=EwlpDwAAQBAJ&pg=PT726&lpg=PT726&dq=havok+collision+tracking&source=bl&ots=Eav72q2T95&sig=ACfU3U15UvAqvf4FmjYKOAsm1CPMlyaFQA&hl=en&sa=X&ved=2ahUKEwi559zSgJDmAhXHnuAKHQv0ATAQ6AEwCXoECAwQAQ#v=onepage&q=havok%20collision%20tracking&f=false

adelriosantiago
  • 7,762
  • 7
  • 38
  • 71
  • Thanks for this. I tried pushing to arrays already but because collisions/overlaps happen for a number of milliseconds, the pairs were being added over and over again. I am now trying a version using pairs as an object where the array is checked first to make sure they have not already been added. https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist – matski Nov 24 '19 at 09:06