moveWithCollisions performance

I’m having major performance issues with my game, and I narrowed it down to collisions. So I setup a basic PG to isolate the issue: https://playground.babylonjs.com/#8P52UN#1.

I’m seeing median times of 1-2ms in Safari, with max times reaching 6ms! For just one call to moveWithCollisions.
Screenshot 2023-12-23 at 10.16.40 AM

Chrome is much faster, but still, a median of 0.3ms for one call is a lot.
Screenshot 2023-12-23 at 10.19.14 AM

These times were recorded on a '19 MBP. Imagine iPhone times. :confused:

Am I using moveWithCollisions wrong? Is there anything we can do to improve its performance?

I don’t really see what’s wrong with performance. This function detects collisions, so there are necessarily calculations which cost a little.

2ms per call is not a little. We only have 16ms per tick, and after everything else the engine does, there’s only about 10ms available for the game logic. So a single 2ms call is 20% of the available time. And that’s on average. With many calls taking 5ms, in reality we’re dropping every other frame… on a desktop! On a phone, it’s completely unplayable.

800 tris are a lot for collisions checking. You don’t need collisions check for ground if you want to place your objects under the ground. Just use getHeightAtCoordinates GroundMesh | Babylon.js Documentation

For other objects you should optimize the count of tris. You can enable/disable checkCollisions based on the distance between the player and the static object(rocks, buildings etc.) Also, you should use for simple shape(box) for reducing tris count.

2 Likes

I just noticed that the object sometimes falls through the ground when the PG loads - that’s not the intention.

You’re right about the number of triangles. Reducing subdivisions on the ground mesh from 20 to 10 lowered the average time to 0.3 - 0.5 ms (in Safari).

The worst case is still still 3 - 4 ms though. That’s not only slow enough to still cause problems, it’s nearly 10x variance. Not good.

In my case I’m using 2d for collisions checking, because I don’t need Y axis. Anyway for large amount of objects you definitely need to use grid-based/octree for partitioning.