Getting nearest vehicle in range
#1

I've been trying to make a function that gets the nearest vehicle within 10 meters, so far i only got the nearest vehicle, but don't know how to add the range to it.

Here's the current function:
pawn Код:
stock GetNearestVehicle(playerid)
{
    new Float:dist = 1000.0;
    new targetid = INVALID_PLAYER_ID;
    new Float:x1,Float:y1,Float:z1;
    new Float:x2,Float:y2,Float:z2;
    new Float:tmpdis;
    GetPlayerPos(playerid,x1,y1,z1);
    for(new i=0;i<MAX_PLAYERS;i++)
    {
        if(i == playerid) continue;
        GetPlayerPos(i,x2,y2,z2);
        tmpdis = floatsqroot(floatpower(floatabs(floatsub(x2,x1)),2)+floatpower(floatabs(floatsub(y2,y1)),2)+floatpower(floatabs(floatsub(z2,z1)),2));
        if(tmpdis < dist)
        {
            dist = tmpdis;
            targetid = i;
        }
    }
    return targetid;
}
Reply
#2

Why not loop through all vehicles and see if the player is close to any of them? You would just loop through all possible IDs (2000) and then do https://sampwiki.blast.hk/wiki/GetPlayerDistanceFromPoint with https://sampwiki.blast.hk/wiki/GetVehiclePos.
Reply
#3

pawn Код:
stock GetNearestVehicle(playerid, Float:max_range = 99999.0)
{
    new Float:closestDist = max_range;
    new closestVehicle = 0;
    new Float:thisDist;
   
    new Float:x, Float:y, Float:z;
    GetPlayerPos(playerid, x, y, z);
   
    for(new i=1; i<=MAX_VEHICLES; i++)
    {
        thisDist = GetVehicleDistanceFromPoint(i, x, y, z);
        if(thisDist < max_range && thisDist < closestDist)
        {
            closestDist = thisDist;
            closestVehicle = i;
        }
    }
    return closestVehicle;
}
Not tested, but it compiles, and it should work.

If it returns 0 (invalid vehicle ID as they start at 1) it means there's no vehicles within range.
Reply
#4

Quote:
Originally Posted by MP2
Посмотреть сообщение
pawn Код:
stock GetNearestVehicle(playerid, Float:max_range = 99999.0)
{
    new Float:closestDist = max_range;
    new closestVehicle = 0;
    new Float:thisDist;
   
    new Float:x, Float:y, Float:z;
    GetPlayerPos(playerid, x, y, z);
   
    for(new i=1; i<=MAX_VEHICLES; i++)
    {
        thisDist = GetVehicleDistanceFromPoint(i, x, y, z);
        if(thisDist < max_range && thisDist < closestDist)
        {
            closestDist = thisDist;
            closestVehicle = i;
        }
    }
    return closestVehicle;
}
Not tested, but it compiles, and it should work.

If it returns 0 (invalid vehicle ID as they start at 1) it means there's no vehicles within range.
It give's me an invalid vehicle ID (28 in my case) but there are over 10 vehicles in range of it.
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)