Java – How to find the distance between two objects in libgdx

How to find the distance between two objects in libgdx… here is a solution to the problem.

How to find the distance between two objects in libgdx

In my LibGdx game, I have ModelInstances and I need to know how far they are from.
I tried using Transform.getTranslation(new Vector3) but it returned translations of the model. I haven’t found a way to get the global location of the model.

Solution

To get the distance between two vectors, use the dst method:

public float dst(Vector3 vector)
Specified by:
dst in interface Vector<Vector3>
Parameters:
vector - The other vector
Returns:
the distance between this and the other vector

Vector3 reference

The best way to keep track of a model is to create a wrapper to store the object position (Vector3) and rotation (Quaternion), and set the model position on the render method in that wrapper, as follows:

public abstract class ModelWrapper{

private ModelInstance model;
    private Vector3 position;
    private Quaternion rotation;

public ModelWrapper(ModelInstance model,Vector3 position,Quaternion rotation) {
        this.model = model;
        this.position = position;
        this.rotation = rotation;
    }

public ModelInstance getModel() {
        return model;
    }

public void setModel(ModelInstance model) {
        this.model = model;
    }

public Vector3 getPosition() {
        return position;
    }

public void setPosition(Vector3 position) {
        this.position = position;
    }

public Quaternion getRotation() {
        return rotation;
    }

public void setRotation(Quaternion rotation) {
        this.rotation = rotation;
    }

public void render(ModelBatch modelBatch, Environment  environment) {
        this.model.transform.set(this.position,this.rotation);
        modelBatch.render(model, environment);
    }
}

Related Problems and Solutions