Question

Hi so okay put it this way. We have 12 players well what I want to do is find the closest one.

I've written some code below; two versions of my attempt (trust me theirs been a lot more, could of written a bible by now)

/*int client::closestEnemy()
{
    for(u32 i = 0; i<12; i++)
    {
        DbgPrint("i: %i\n", i);
        u32 index = 0;
        if(!p[i].exist() || !p[i].alive() || p[i].team() == 3 || i == s.index) 
                 continue;

        for(u32 o = 0; o<12; o++) 
                 if(vec.distance(*pos(), *p[i].pos()) <= vec.distance(*pos(), *p[o].pos()) || vec.distance(*pos(), *p[i].pos()) == vec.distance(*pos(), *p[o].pos()))
                       index++;
        DbgPrint("PLAYER %s INDEX = %i\n", p[i].readName(), index);

        if(index>10)  
            return i;

        index = 0;
    }
    return -1;
}*/


int client::closestEnemy()
{
    float distacnes[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    u32 index = 0;
    for(u32 i = 0; i<12; i++)
        if(p[i].exist() || p[i].alive() || p[i].team() != 3 || i != s.index) 
             distacnes[i] = vec.distance(*pos(), *p[i].pos()); 
        else 
             continue;

    for(u32 i = 0; i<12; i++) 
         if(distacnes[i]<distacnes[i+1]) 
             index++;

    DbgPrint("Score = %i\n", index);

    if(index>11) 
        return index;

    return -1;
}

What I am doing is simply increment index by 1 when ever another clients distance is larger then mine.

Now the first one is best bet but sometimes does not create a high enough index which makes zero sense because at least one client has to have a smaller distance then everyone else.

Was it helpful?

Solution

First, some indentation would help, I guess. Then, there's no need to store all distances. You can keep track of the minimum distance encountered so far, like this:

int client::closestEnemy()
{
    int index = -1;
    float minDistance;
    for(u32 i = 0; i<12; i++) {
        if(p[i].exist() || p[i].alive() || p[i].team() != 3 || i != s.index) {
            float distance = vec.distance(*pos(), *p[i].pos());
            if (index == -1 || distance < minDistance) {
                index = i;
                minDistance = distance;
            }
        }
    }

    return index;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top