Darin Beaudreau Darin Beaudreau - 5 months ago 15
Java Question

Moving an object in a periodical circular path around a point

I'm working on a game for a game jam right now, and the problem is related to the flight path of a certain game enemy. I'm trying to have several of them fly in formation, and the idea was to have them fly in a wide radius circle around the center of the screen so they essentially box in the player. To do this, I tried to use the following formula...

public Pair<Double> move(Pair<Double> currPos, Pair<Double> playerPos) {
Pair<Double> newPos = new Pair<>(currPos.x, currPos.y);

// The radius used as the distance from the center.
double r = (Framework.CANVAS_WIDTH / 2) - Player.SHIP_SIZE;
// X,Y coords for center of the screen.
double cX = (Framework.CANVAS_WIDTH / 2);
double cY = (Framework.CANVAS_HEIGHT / 2);
// Trigonometric equation for transforming the object in a circle.
newPos.x = cX + (r * Math.cos(Framework.getHypotenuse(currPos, new Pair<Double>(cX, cY)) + (Math.PI / 90)));
newPos.y = cY + (r * Math.sin(Framework.getHypotenuse(currPos, new Pair<Double>(cX, cY)) + (Math.PI / 90)));

return newPos;

I can't figure out why the equation doesn't seem to work. When I test the movement pattern, there seem to be two enemies on screen rotating around the center, even though I only spawned one. However, they're blinking really fast, which makes it seem like maybe the ship is jumping back and forth really fast. This is supported by the fact that when I took a screenshot, there was only one ship. Is there something wrong with my trigonometry that would cause this, or does the problem lie elsewhere?


The following pseudocode gives the standard way to make an object move in a circular path:

double r  = (...);  // Radius of circle
double cX = (...);  // x-coordinate of center of rotation
double cY = (...);  // y-coordinate of center of rotation

double omega = (...);  // Angular velocity, like 1
double t = (...);  // Time step, like 0.00, 0.01, 0.02, 0.03, etc.

newPos.x = cX + r * Math.cos(t * omega);
newPos.y = cY + r * Math.sin(t * omega);