Skip to content

Mundus jBullet btMotionState

antz edited this page Aug 11, 2023 · 1 revision

Below is an extended btMotionState class for Mundus GameObjects. The bullet physics engine will update the location and rotation of your GameObjects automatically. TODO: Maybe a good idea to add a bullet example in the example project.

import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.linearmath.btMotionState;
import com.mbrlabs.mundus.commons.scene3d.GameObject;

public class GameObjectMotionState extends btMotionState {
    private static final Vector3 tmp = new Vector3();
    private static final Quaternion tmpQuat = new Quaternion();
    private static final Matrix4 tmpMat = new Matrix4();

    GameObject gameObject;

    public GameObjectMotionState(GameObject gameObject) {
        this.gameObject = gameObject;
    }

    @Override
    public void getWorldTransform (Matrix4 worldTrans) {
        worldTrans.set(gameObject.getPosition(tmp), gameObject.getRotation(tmpQuat));
    }

    @Override
    public void setWorldTransform (Matrix4 worldTrans) {
        // GameObjects rely on vectors, so we update their vectors and not a matrix.
        Matrix4 worldToLocal = tmpMat.set(worldTrans).mulLeft(gameObject.getParent().getTransform().inv());
        worldToLocal.getTranslation(tmp);
        worldToLocal.getRotation(tmpQuat, true);

        gameObject.setLocalPosition(tmp.x, tmp.y, tmp.z);
        gameObject.setLocalRotation(tmpQuat.x, tmpQuat.y, tmpQuat.z, tmpQuat.w);
    }
}