Question

For a game I'm writing I need to find an integer value for the distance between two sets of coordinates. It's a 2D array that holds the different maps. (Like the original zelda). The further you go from the center (5,5) the higher the number should be since the difficulty of enemies increases. Ideally it should be between 0 and 14. The array is 11x11.

Now, I tried to use the pythagoras formula that I remember from highschool, but it's spewing out overflow numbers. I can't figure out why.

        srand(rand());
        int distance=sqrt(pow((5-worldx), 2)-pow((5-worldy), 2));
        if(distance<0) //alternative to abs()
        {
            distance+=(distance * 2);
        }
        if(distance>13)
        {
            distance=13;
        }

        int rnd=rand()%(distance+1);

        Monster testmonster = monsters[rnd];
Was it helpful?

Solution

srand(rand()); does not make sense, it should be srand(time(NULL));

don't use pow for square, just use x*x

your formula is also wrong, you should add number together not minus

sqrt return double and cast to int will round it down

i think sqrt always return positive number

you know abs exists right? why not use it? also distance = -distance is better than distance+=(distance * 2)

srand(time(NULL));

int dx = 5 - worldx;
int dy = 5 - worldy;
int distance=sqrt(dx * dx + dy * dy);
if(distance>13)
{
    distance=13;
}

int rnd=rand()%(distance+1);

Monster testmonster = monsters[rnd];

OTHER TIPS

It's a^2 + b^2 = c^2, not minus. Once you call sqrt with a negative argument, you're on your own.

You're subtracting squares inside your square root, instead of adding them ("...-pow...").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top