# Solved Get nearest player?

Comments in 'Plugin Development' started by Legoboy0215, Jun 30, 2015.

Not open for further replies.
1. Offline

### Legoboy0215Notable Member

Joined:
Nov 1, 2014
Posts:
1,723
Minecraft User:
In terms of coding, how do I find the nearest player from the command executor??
2. Offline

### PEMapModderNotable MemberPlugin Developer

Joined:
Oct 9, 2013
Posts:
7,293
Plugins:
11
Minecraft User:
Did you mean command sender/issuer?
PHP:
``` if(\$sender instanceof Position){ // if the sender is a position, for example a player  \$closest = null;  \$lastSquare = -1;  foreach(\$sender->getLevel()->getPlayers() as \$p){ // for every player in the sender's world    if(\$p !== \$sender){      \$square = \$sender->distanceSquared(\$p); // get the square of the distance between the sender and the currently checking player      // use distanceSquared() because it is faster than distance()      if(\$lastSquare === -1 or \$lastSquare > \$square){ // this is the so far closest player        \$closest = \$p;        \$lastSquare = \$square;      }    }  }  // do something with \$closest  // \$closest may be null if there are no players in the world except \$sender} ```
Last edited by a moderator: Jun 30, 2015
Falk, aliuly and TonyDroide like this.
3. Offline

### XenturioActive Member

Joined:
Sep 19, 2014
Posts:
333
Minecraft User:
PHP:
``` foreach(\$p->getLevel()->getNearbyEntities(new AxisAlignedBB(\$pos->getX()-10, \$pos->getY()-10, \$pos->getZ()-10, \$pos->getX()+10, \$pos->getY()+10, \$pos->getZ()+10), \$p) as \$entity) ```
Falk likes this.
4. Offline

### Legoboy0215Notable Member

Joined:
Nov 1, 2014
Posts:
1,723
Minecraft User:
I want to teleport the sender to the closest player. I think I am only missing the teleportation. What value should I use?
5. Offline

### PEMapModderNotable MemberPlugin Developer

Joined:
Oct 9, 2013
Posts:
7,293
Plugins:
11
Minecraft User:
Read the code I gave you and try to understand it. You are welcome to ask any questions about the code itself, but before you do, don't try to add it into your code.
Legoboy0215 and CrazedMiner like this.
6. Offline

### Legoboy0215Notable Member

Joined:
Nov 1, 2014
Posts:
1,723
Minecraft User:
I never even tried.
7. Offline

### PEMapModderNotable MemberPlugin Developer

Joined:
Oct 9, 2013
Posts:
7,293
Plugins:
11
Minecraft User: