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]);
}
bug.angle = (atan(slope)*RAD2DEG);
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);
A simple math problem too long to describe in the subject
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:
so, can anyone be so kind as to tell me the inaccuracy in my math?
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!).
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!).
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.]
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.]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement