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

This topic is 4864 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
converting back to radians. I would just calculate bug.angle in radians, and then add that focus thing in radians as well.

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:

bug.angle = atan2(item.position[1]-bug.position[1], item.position[0]-bug.position[0])*RAD2DEG;

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.

[Edit: what sporadic said.]

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

1. 1
Rutin
22
2. 2
3. 3
4. 4
5. 5

• 9
• 9
• 9
• 14
• 12
• ### Forum Statistics

• Total Topics
633308
• Total Posts
3011293
• ### Who's Online (See full list)

There are no registered users currently online

×