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->x;
double dy = y - this->y;
this->th = atan(dy / dx);
if (isnan(this->th)) {
this->th = 0;
return;
}
if (dx < 0) {
this->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 >= mj_distance(this->x, this->y, x, y)) {
this->x = x;
this->y = y;
} else {
mj_dot_rotate(this, x, y);
this->x += d * cos(this->th);
this->y += d * sin(this->th);
}
}