Algorithm to follow a point This code basically makes the dot follow a certain point on the screen. It consumes a significant amount of computing time in my game, so I'd like it to be best optimized. I wrote this code after quickly reading some pages in a high school mathematics book, so it's unlikely to be a computationally efficient solution.

The mj_ prefix is just what I use instead of a namespace in my C code.

Suggest some good possible optimizations.

struct mj_dot {
    double x;
    double y;
    double th;
};

void mj_dot_rotate(struct mj_dot *, double, double);
void mj_dot_move(struct mj_dot *, double, double, double, double);

static double mj_distance(double x, double y, double x2, double y2) {
    return sqrt(pow(x - x2, 2) + pow(y - y2, 2));
}

void mj_dot_rotate(struct mj_dot *this, double x, double y) {
    double dx = x - this-&gt;x;
    double dy = y - this-&gt;y;
    this-&gt;th = atan(dy / dx);
    if (isnan(this-&gt;th)) {
        this-&gt;th = 0;
        return;
    }
    if (dx &lt; 0) {
        this-&gt;th += MJ_MATH_PI;
    }
}

void mj_dot_move(struct mj_dot *this, double x, double y, double speed, double seconds) {
    double d = speed * seconds;
    if (d &gt;= mj_distance(this-&gt;x, this-&gt;y, x, y)) {
        this-&gt;x = x;
        this-&gt;y = y;
    } else {
        mj_dot_rotate(this, x, y);
        this-&gt;x += d * cos(this-&gt;th);
        this-&gt;y += d * sin(this-&gt;th);
    }
}
pow(x,2) is less efficient than simply multiplying with itself:

static double mj_distance(double x, double y, double x2, double y2) {
    double dx = x - x2;
    double dy = y - y2;
    return sqrt(dx*dx + dy*dy);
}


However because you just compare it against a distance you can do away with the square root and compare it against the square of the distance:

double d = speed * seconds;
if (d*d &gt;= mj_distance_squared(this-&gt;x, this-&gt;y, x, y)) {


there is a atan2 function which takes a delta y and delta x to return the correct angle.

void mj_dot_rotate(struct mj_dot *this, double x, double y) {
    double dx = x - this-&gt;x;
    double dy = y - this-&gt;y;
    this-&gt;th = atan2(dy, dx);
}