0

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.

genpfault
  • 51,148
  • 11
  • 85
  • 139
Fishie
  • 13
  • 1
  • Recommendation: If you're going to do much with game physics and graphics, get good at math. You literally have no other choice. This shit is ALL math. – user4581301 Apr 20 '23 at 17:59
  • 1
    The formula looks correct (except get used to storing angles in radians). *"what exactly would be the x and y centres"* The center of the circle. You tell us what that is. *"what exactly would the theta be"* The angle along the circle (0 = right, 90 = down or up, depending on which way your +Y is pointing). – HolyBlackCat Apr 20 '23 at 18:05
  • Can you perhaps show us the desired trajectories as a picture. – HolyBlackCat Apr 20 '23 at 18:20
  • See also [gamedev.se]. – Thomas Matthews Apr 20 '23 at 20:53

1 Answers1

0

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.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36