# A simple math problem too long to describe in the subject

This topic is 4933 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

well, I have been making a simple screen saver where a bunch of ants with random locations all head toward an item which is randomly placed on the screen, and their path meanders to a maximum of +- 5 degrees based on how focused they are to get their. The problem is that the closer they get to the item, the more sparatic their movement to the point that when they are about 40 pixels away, they all just vibrate in place in a circle around the object. the math I came up with last night is as follows:
if(item.position[0]-bug.position[0] == 0.0f){
slope = 99999999999999.9;
}else{
slope = (double)(item.position[1]-bug.position[1])/(float)(item.position[0]-bug.position[0]);
}

change = rand()%bug.focus;
if(change == 1){
bug.angle += sin(rand())*(10-bug.focus);
}

bug.position[0] += bug.speed*cos(bug.angle);
bug.position[1] += bug.speed*sin(bug.angle);


so, can anyone be so kind as to tell me the inaccuracy in my math?

##### Share on other sites
I see a couple of things:

You calculate bug.angle in degrees, but then calculate cos and sin with it, without

You don't need the slope, just use atan2(deltaY, deltaX) function. It automatically takes care of the CAST rule, without which the angle is incorrect (slope doesn't uniquely determine angle!).

##### Share on other sites
Don't have the answer to your question, but I'd replace the first 6 lines with something like this:

Now that I think about it, why are you converting to degrees if you're going to be calling sin() and cos() later? Anyway, this method will only fail if the ant is practically on top of the target, a condition you can check for easily.

##### Share on other sites
thanks, that cleared the problem right up.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 11
• 9
• 9
• 42
• ### Forum Statistics

• Total Topics
634131
• Total Posts
3015716
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!