 # [SOLVED] Get list of entities near the player?

Hi, whats the best way to get entities that are near the player and calculate each ones triangles returning sum of all? In a defined radius

The easiest way would be to tag the entities that you would generally be interested in, get those entities with findByTag.

Iterate through those entities and get the distance from the player, if it’s within the radius, calculate the triangles

1 Like

Okay, Vec3 v1.distance(v2); does return and display the correct distances but how do I return entities later on? As distance only returns numbers

if (Player.distance(Placements) > 20) {
???

There are several ways to do that. One way is to use a secondary object like this:

``````var enemies = pc.app.root.findByTag('enemy');
var playerPos = new pc.Vec3(0, 10, 0);

var listToShort = enemies.map(o => {
return {
entity: o,
distance: 0.0
};
});

// --- calculate the distance for each entity from the player pos
listToShort.forEach(o => {
o.distance = o.entity.getPosition().distance(playerPos);
});

// --- short from closest to furthest
listToShort.sort((a, b) => a.distance - b.distance);

// --- get the closest entity, it's the first one
// --- in the same way you can filter and get the entities up to a distance
const enemyCloseToPlayer = listToShort;
``````
1 Like

Nice peace of code but > or < returns true or false unfortunately

This is it:

``````var nearPlacements = [];
var closestDistance = 30;
playerPosition = this.player.getPosition();
var placements = this.app.root.findByTag('Placement');
placements.forEach( function(placementsEntity){
var distance = playerPosition.distance(placementsEntity.getPosition());
if (distance < closestDistance) {
nearPlacements.push(placementsEntity);
}
}.bind(this));

if (nearPlacements.length == 0) {
console.log('No near entities');
//Set checker variable to 'True'
} else {
var totalTriangles = 0;
for (var i = 0; i < nearPlacements.length; i++) {
var meshInstances = nearPlacements[i].model.model.meshInstances;
var mat;
var matEach = 0;
for (var i2 = 0; i2 < meshInstances.length; i2++) {
mat = parseFloat(meshInstances[i2].mesh.indexBuffer.numIndices / 3);
matEach += mat;
}
totalTriangles += matEach;
}
console.log(totalTriangles);
}

``````

We can mark this as solved!
Thanks for pointing me out to the right directions

2 Likes