Thread: nearest player
View Single Post
Old 21/06/2015, 04:43 AM   #8
SickAttack
High-roller
 
Join Date: Dec 2013
Posts: 4,769
Reputation: 754
Default Re: nearest player

Well, if you want the function to return the closest player solely; then here you go:
pawn Code:
// [ DEVELOPMENT GAMEMODE ]

// INCLUDES:

#include <a_samp>
#include <foreach>
#include <zcmd>

// MAIN:

main()
{
    print("Development Mode: closest_player_to_player.amx");
}

// CALLBACKS:

public OnGameModeInit()
{
    return 1;
}

public OnGameModeExit()
{
    return 1;
}

// COMMANDS:

CMD:closestplayer(playerid, params[])
{
    new string[144], closest_player = GetClosestPlayerToPlayer(playerid);
    if(closest_player == -1)
    {
        strcat(string, "No players have been found.");
        SendClientMessage(playerid, -1, string);
    }
    else
    {
        new Float:x, Float:y, Float:z, Float:distance;
        GetPlayerPos(playerid, x, y, z);
        distance = GetPlayerDistanceFromPoint(closest_player, x, y, z);

        format(string, sizeof(string), "%s (%d) is the closest player to you (%0.2f meters).", PlayerName(closest_player), closest_player, distance);
        SendClientMessage(playerid, -1, string);
    }
    return 1;
}

// FUNCTIONS:

stock GetClosestPlayerToPlayer(playerid)
{
    new Float:x, Float:y, Float:z, closest_player = -1, Float:distance, Float:temp;
    GetPlayerPos(playerid, x, y, z);

    foreach(new i: Player)
    {
        if(i == playerid) continue;

        if(closest_player != -1)
        {
            temp = GetPlayerDistanceFromPoint(i, x, y, z);

            if(temp < distance)
            {
                closest_player = i;
                distance = temp;
            }
        }
        else
        {
            closest_player = i;
            distance = GetPlayerDistanceFromPoint(i, x, y, z);
        }
    }
    return closest_player;
}

stock PlayerName(playerid)
{
    new name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof(name));
    return name;
}
SickAttack is offline   Reply With Quote