Advertisement Jump to content
Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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;
    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);

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

Share this post

Link to post
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 this post

Link to post
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 this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. 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!