首页 文章

用Java在一个对象周围旋转

提问于
浏览
1

**


Goooglers 记得使用tx.setToRotation(Math.toRadians(angle));当使用李的方法时 .

**

我正在制作一种基于细胞的游戏,其中每个“有机体”由多个10x10像素的平方(细胞)组成,这些细胞必须连接到“主细胞”,否则它们将被移除 . 主单元格中包含一个表示其角度(0-360 . )的int,当主单元格旋转时,它必须将所有连接的单元格与之对齐 . 吼叫的例子

Cells rotated 0 degrees

Cells rotated 120 degrees

我已经可以在这个角度绘制它们,我只需要Cell的函数getX()和getY()来返回基于主单元格旋转的修改后的X / Y.

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)?

1 回答

  • 1

    查看AffineTransform类,它为各种转换提供了易于使用的方法,包括旋转 . 然后使用您的(x,y)值构造Point2D并应用AffineTransform以获得旋转的新Point2D . 这很好,因为它的用法与您当前用于旋转图形上下文的用法非常相似 .

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

    额外奖励:您可以使用变换进行渲染和计算!您可以在Graphics2D对象上应用AffineTransform以减少类似/重复的代码 .

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

相关问题