Search code examples
javaandroid3dlibgdx

How to find distance beetwen two objects in libgdx


In my LibGdx game i have waypoins(ModelInstance) and i need to know the distance beetwen them. I tryed to use Transform.getTranslation(new Vector3) but it returns the translation of model. I have't found methods to get Global position of 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 track your model is create a wrapper that stores your object position (Vector3) and rotation (Quaternion) and in this wrapper set the model position on your render method, something like this:

    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);
        }
    }