Callback within unregisterOnPhysicsCollide

I’m trying to understand the point of the callback within the “unregisterOnPhysicsCollide”. I saw this in the bugs section: physicsImpostor.unregisterOnPhysicsCollide not working?! and it kind of makes sense.

I assume that by ‘unregistering’ an impostor(s) you don’t want to track when a collision happens anymore, but I’m confused on when the callback would even be used in that sense.

This is how I currently have it setup:

DetectCollisions(): void {

    this.hasCollided = false;

    this.sphere.physicsImpostor.registerOnPhysicsCollide(

      [this.ground.physicsImpostor],

      () => {

        if (!this.hasCollided) this.DisableSphere();

        this.hasCollided = true;

      }

    );

  }

  DisableSphere(): void {

    this.sphere.physicsImpostor.unregisterOnPhysicsCollide(

      [this.ground.physicsImpostor],

      () => {

        console.log("unregistered");

      }

    );

    setTimeout(() => {

      this.sphere.setEnabled(false);

    }, 1000);

  }

I know I’m probably overthinking it, but why would you use a callback in the unregisterOnPhysicsCollide?

On a similar note, if I use “setEnabled(false)” on a mesh with a physics impostor would I need to unregister the collisions or would that happen automatically if it’s disabled?

You can register several callbacks with registerOnPhysicsCollide so you need to define which callback to remove with unregisterOnPhysicsCollide:

this.sphere.physicsImpostor.registerOnPhysicsCollide(foo);
this.sphere.physicsImpostor.registerOnPhysicsCollide(foo2);
this.sphere.physicsImpostor.registerOnPhysicsCollide(foo3);
...
this.sphere.physicsImpostor.unregisterOnPhysicsCollide(foo);

Regarding setEnabled, it will only affect rendering. The impostor will remain in the physic simulation.

Ok, I think I get it now. So when you use an arrow function as I had in my code, those functions were completely different. With the registerOnPhysicsCollide, if I create a function, it gets registered and called whenever there is a collision. By using the unregisterOnPhysicsCollide, using the same function as the callback I’ll no longer be calling it whenever a collision is made.

For the setEnabled, is there a way to ‘destroy’ the entire object including the mesh and the impostor? For example, if I wanted to create a grenade that exploded. What would be the most efficient way to do this? Do I need to ‘dispose’ the sphere (mesh) and physics impostor separately?

Correct! (but you cannot use an arrow function but the same variable. If you use a second arrow function even if it is the same code it will be seen as a different variable and thus NOT removed from the list of callbacks)

If you dispose a mesh it will dispose the impostor

Great thank you! Marked solution.

1 Like