Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by fugufish

is there a function that gets the nearest Entity to the player?

like, for eg. There are 3 entities in the vicinity of the player. getNearestEntity would return the closest one out of the three.

1 decade ago by dominic

There's no built in method, no. For Z-Type I just checked all entities - this works fine as long as you don't have thousands of entities in a level.

Use this as a method of your player entity:
findNearestEntity: function() {
	var nearestDistance = Infinity;
	var nearestEntity = null;
	for( var i = 0; i < ig.game.entities.length; i++ ) {
		var ent = ig.game.entities[i];
		var distance = this.distanceTo( ent );
		if( distance < nearestDistance && ent != this ) {
			nearestDistance = distance;
			nearestEntity = ent;
		}
	}
	return nearestEntity;
}

If you have a lot of entities (say > 500), you could also create an invisible entity that has the same center position as your player, but a much larger size. You could then use this entity&039;s #check() method to find the nearest entity that overlaps with it. Because check() uses a spacial hash to look for overlapping entities, this might be faster.
Page 1 of 1
« first « previous next › last »