I am making a simple 2d arcade shooter game and am attempting to have the enemy sprites move in circular patterns.
The enemy's position on the screen is controlled by the two variables: iCurrentScreenX and iCurrentScreenY which are updated and then passed into a separate drawing function.
The issue I have is I can't seem to figure out how have the enemies move in a circular path without them just flying off in random directions. I have found the following formula and attempted to implement it but to no avail:
m_iCurrentScreenX = x_centre + (radius * cos(theta * (M_PI / 180)));
m_iCurrentScreenY = y_centre + (radius * sin(theta * (M_PI / 180)));
I guess my main question is, if you wanted the enemies to move in a circular pattern, what exactly would be the x and y centres, and what exactly would the theta be? (Say for instance I only wanted to use a radius of 32px). And is this formula even correct in the first place?
Each enemy is a 16x16 sprite moving along a 320x500 screen.
Okay, in your formulae, x_center and y_center are the center of the circle you're flying. You decide that. So here's some code that might do what you want.
void flyInCircles(double xCenter, double yCenter, double radius) {
// Theta is the current angle in radians, not degrees
double theta = 0.0;
double twoPi = M_PI * 2.0;
double rate = twoPi / 60; // This is how far we'll move per step.
while (true) {
theta += rate;
if (theta >= twoPi) {
theta -= twoPi;
}
double thisX = xCenter + (radius * cos(theta) );
double thisY = yCenter + (radius * sin(theta) );
// draw your sprite at (thisX, thisY)
std::thread::this_thread.sleep_for(10ms);
}
}
This should fly around in circles, moving 1/60th of a circle every 10 ms.