Internal collision system acting weird after calling mesh.dispose()

Hi there,

Context: I am developing a third person platformer game where the player can move a mesh using the WASD keys. I use the moveWithCollisions() function on the mesh and the internal collision system to handle all collision with objects. My game includes player crouching/standing on a button press, which I’ve solved by disposing the mesh with mesh.dispose() and re-creating it in a different shape.

Bug: Usually, whenever I press my mesh into an angled shape (like a tilted box), the collision handling works as expected, meaning the mesh more or less stays at the same vertical position, and doesn’t sink into the ground. However, after dispoing the mesh and re-creating it, the collision system is acting very strange. If I move my mesh back into the angled shape, the mesh now sinks into the ground. Strange, huh?
I have tried to run my code on several versions of babylonjs, including the newest 5.0.0, but the bug still persists.

Playground link to reproduce: https://playground.babylonjs.com/#KBS9I5#2192

Steps to re-produce bug:

  1. With WASD, move the player (cylinder) into the angled box straight ahead
    Notice how the collision system prevents us from sinking into the ground
  2. Press ‘Space’ to trigger mesh.dispose() and re-create the player mesh
  3. Move the player back into the angled box and notice how the cylinder
    now sinks into the ground when moving it repeatedly.

Additional notes: The bug doesn’t occur if I use mesh.setEnabled(false) instead of mesh.dispose(). Furthermore, I tried messing around a bit, and for some reason the bug does not occur if I dispose of a random box before disposing of (and re-creating) the mesh. So weird.
For now I chose to fix this issue by creating the two different meshes I need initially and then switch between them using the setEnabled function, but I’m still incredibly curious what could be triggering this bug.

2 Likes

pinging @Cedric to solve the mystery :wink:

1 Like

I’m adding this issue to my todo list!

4 Likes

I played a bit with the PG and my guess is the order of collision detections in the code makes the response to differ.
If the player mesh is created after the ground and the inclined box, then recreating the player mesh is fine:

Create a Simple World Series | Babylon.js Playground

1 Like

Ah that’s interesting! Thanks for finding a fix, I’ll make sure to remember that.

Cheers

I’ve exposed a retryCount variable. It’s 3 by default and increasing it to 4 solves the issue. It also solves some jittering when colliding.

So, in the PG, add this line :

playerMesh.collisionRetryCount = 4;

In the drawPlayerMesh function.

2 Likes