How can I check for a mesh using a position?

Hello there! I want to check for a mesh in a position.
For example: I want to get a mesh at 10, 10, 10 (knowing that the mesh width and height are 1).
Is that possible in BabylonJS?

Hello @EnderAdel :slight_smile:
Quite simple, this should do the trick.
Note that only the first match is returned, any overlapping meshes may give a unwanted or unexpected result.

function isBetween( nb, min, max) {
  return nb >= min && nb <= max;
}

BABYLON.Scene.prototype.getMeshAtPosition = function ( x, y, z, uniformSize){
  // Half size (-/+ half size to min/max range)
  let halfUniformSize = 0.5 * (uniformSize ? uniformSize : 1); // Default 1 (0.5) (1width 1height  1depth)
  for(let i = 0; i < this.meshes.length; i++){
    // Mesh position
    let mP = this.meshes[i] && !this.meshes[i].isDisposed() ? this.meshes[i].position : null;
    // Check if position matches
    if( mP 
    && isBetween(mP.x, x - halfUniformSize, x + halfUniformSize)
    && isBetween(mP.y, y - halfUniformSize, y + halfUniformSize)
    && isBetween(mP.z, z - halfUniformSize, z + halfUniformSize) ){
      return this.meshes[i];
    }
  }
};

// Use
yourSceneVar.getMeshAtPosition( 0, 1, 0)
yourSceneVar.getMeshAtPosition( 0, 1, 0, 2) // with a "non-standard" size of 2, rather than default 1.

I hope the naming / comments are self-explaining, otherwise, do ask :slight_smile:

1 Like