Caelum
Caelum

Reputation: 852

Rotate one object around another in Java

**


Goooglers remember to use tx.setToRotation(Math.toRadians(angle)); when using Li's method.

**

I'm making a cell-based game in which every "organism" consists of multiple 10x10 pixel sqaures(cells), these cells must be connected to a "main cell" otherwise they are removed. the main cell holds a int which represents it's angle(0-360.), when the main cell rotates it has to align all of the connected cells with it. example bellow

Cells rotated 0 degrees Cells rotated 120 degrees

I can already draw them on this angle, I just need the functions getX() and getY() of Cell to return a modified X/Y based off the main cell's rotation.

Given the main cells angle(int angle), the offset of given Cell(int xMod, int yMod) and current location (int x, int y) can you make a getter and setter for Cell which returns a X and Y modified to suit the rotation of the main Cell(owner)?

Upvotes: 1

Views: 440

Answers (1)

Zong
Zong

Reputation: 6230

Look into the AffineTransform class, which provides easy to use methods for various tranformations, including rotation. Then construct a Point2D using your (x, y) values and apply the AffineTransform to get a new Point2D that is rotated. This is nice because its usage is very similar to what you're currently using to rotate the graphics context.

AffineTransform tx = new AffineTransform();
tx.rotate(...);

Point2D point = new Point2D.Double(x, y);
Point2D rotated = new Point2D.Double();
tx.transform(point, rotated);

Bonus: you can use the transform for both the rendering and calculations! You can apply the AffineTransform on a Graphics2D object to cut down on similar/duplicate code.

Graphics2D g = ...
g.transform(tx);

Upvotes: 1

Related Questions