Search code examples
callbackcollisionjbullet

How do I execute a callback when JBullet detects a collision?


So currently I have an instance of JBullet running on its own thread and I have no idea how to get information about collisions on JBullet 20101010-1.

I have tried calling ContactAddedCallback as shown below but nothing happens.

new ContactAddedCallback() {

            @Override
            public boolean contactAdded(ManifoldPoint cp, CollisionObject colObj0, int partId0, int index0,
                    CollisionObject colObj1, int partId1, int index1) {
                System.out.println("Collision");
                return false;
            }
        };

Solution

  • you must add ContactAddedCallback to BulletGlobals

    to do that after you create a ContactAddedCallback like this ::

    ContactAddedCallback myCollisionCallback = new ContactAddedCallback() {
    
                @Override
                public boolean contactAdded(
    
                    ManifoldPoint cp, 
                    CollisionObject colObj0, 
                    int partId0, 
                    int index0,
                    CollisionObject colObj1, 
                    int partId1, 
                    int index1) {
    
                    System.out.println("hi i am collision !!");// :|
                    return false;
                }
            };
    

    and add flag to rigidbody like this ::

    rb = new RigidBody(constructionInfo);
    rb.setCollisionFlags(CollisionFlags.CUSTOM_MATERIAL_CALLBACK);
    

    now add to BulletGlobals Like this ::

    BulletGlobals.setContactAddedCallback( myCollisionCallback );

    if you want get which RigidBody are Collided do this ::

    when you create a CollisionShape you must add userPointer like this ::

    BoxShape groundShape = new BoxShape(new Vector3f(1000,10,1000));
    
    rb = new RigidBody(constructionInfo);
        ... 
    groundShape.setUserPointer(rb);
    

    and finaly in ContactaddedCallback you can check like this ::

    ContactAddedCallback myCollisionCallback = new ContactAddedCallback() {
    
        @Override
        public boolean contactAdded(
    
            ManifoldPoint cp, 
            CollisionObject colObj0, 
            int partId0, 
            int index0,
            CollisionObject colObj1, 
            int partId1, 
            int index1) {
    
            if (colObj0.getUserPointer().equals(rb)) {
    
                //for sample you can push them to up
                rb.applyCentralImpulse(new Vector3f(0,1,0));
    
            }
    
            if (colObj1.getUserPointer().equals(rb)) {
    
                rb.applyCentralImpulse(new Vector3f(0,1,0));
    
            }
            System.out.println("hi i am collision !!");// :|
            return false;
        }
    };