Search code examples
libgdxcollision-detectionbullet

Detect collision of btCompoundShape with btSphereShape with Bullet and LibGDX


I'm trying to detect collision between btCompountShape and btSphereShape with Bullet library used in LibGDX project.

My detection method looks like this:

def checkCollision(left: btCollisionObject, right: btCollisionObject) = {
  val leftWrapper = new CollisionObjectWrapper(left)
  val rightWrapper = new CollisionObjectWrapper(right)

  val algorithm = collisionDispatcher.findAlgorithm(leftWrapper.wrapper, rightWrapper.wrapper)

  val info = new btDispatcherInfo()
  val result = new btManifoldResult(leftWrapper.wrapper, rightWrapper.wrapper)

  algorithm.processCollision(leftWrapper.wrapper, rightWrapper.wrapper, info, result)

  val r = result.getPersistentManifold.getNumContacts > 0

  result.dispose()
  info.dispose()
  algorithm.dispose()
  leftWrapper.dispose()
  rightWrapper.dispose()

  r
} 

It works perfectly fine when I use it to detect collision between two btSphereShape objects. But when I pass one that is btCompoundShape it fails. For testing I created my btCompoundShape with only one child shape, namely simple btSphereShape. It fails with following error:

Exception in thread "LWJGL Application" java.lang.NullPointerException
  at com.game.CollisionDetector$class.checkCollision(CollisionDetector.scala:19)
  at com.game.SmlPwsat2Game.checkCollision(SmlPwsat2Game.scala:14)
  at com.game.SmlPwsat2Game.render(SmlPwsat2Game.scala:87)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

I checked that result.getPersistentManifold returns null. Why? And what can I do to make it work?


Solution

  • A btCompoundShape is a compound of multiple shapes. There is no such thing as one algorithm for multiple shapes. You need an algorithm for each shape it is made of against the sphere.

    That being said, you should never even have to care about that, because the collision world takes care of that for you. It looks like you stopped in the middle of my tutorial. The checkCollision method is only intended as example. To show you what's going on. Not to actually use it.

    Check https://xoppa.github.io/blog/using-the-libgdx-3d-physics-bullet-wrapper-part1/, make sure to read the entire tutorial, don't stop in the middle. Later on in the tutorial I show you how to use a collision world and the checkCollision method is removed.