【问题标题】:Rotating a point around another point in a game loop (Java)在游戏循环中围绕另一个点旋转一个点(Java)
【发布时间】:2015-05-22 09:20:10
【问题描述】:

我正在尝试创建一个方法,该方法围绕 Java 中的另一个点旋转我想要制作的 Asteroids 克隆。现在我有 2 个 Point 实例,称为 point 和 center。我的方法的代码是这样的:

public void Rotate(double angle){
       double a; 
       int x,y,distance;
       distance=30;
       a=Math.atan2((int)(point.getX()-center.getX()),(int)(point.getY()-center.getY()));
       a=a+angle;
       x=(int)(Math.cos(a)*distance);
       y=(int)(Math.sin(a)*distance);
       point.setLocation(x,y);   
}

我的游戏循环的代码是这样的:

while (true){
      game.Rotate(10);
      game.repaint();
      Thread.sleep(10);
}

问题是点和中心之间的距离增加或减少,我不知道为什么。有人可以告诉我什么问题吗?

编辑[问题已解决]: 对于任何对此感兴趣的人,我是如何使用从以下答案中获得的帮助解决问题的: 一、Rotate函数:

public void Rotate(double angle){
    double x,y;
    double distance=60;
    x=Math.round(center.getX() + (Math.cos(Math.toRadians(angle))*distance));
    y=Math.round(center.getY() + (Math.sin(Math.toRadians(angle))*distance));
    point.setLocation(x,y);
}

然后我又做了一个叫move的方法:

public void move(){
    angle+=2;
    if(angle>360){
        angle=0;
    }
    Rotate(angle);
}

这是游戏循环代码:

while(true){
        main.move();
        main.repaint();
        Thread.sleep(10);
    }

再次感谢您的支持。

【问题讨论】:

  • y=(int)(Math.sin(a)*distance);
  • 感谢您的回复,但即使这样它仍然无法正常工作。
  • 不确定this 是否有帮助
  • 这实际上解决了我所有的问题。非常感谢。

标签: java rotation geometry game-loop


【解决方案1】:

您围绕坐标原点旋转点。要将其围绕中心旋转,请使用

  x=center.getX() + (int)(Math.cos(a)*distance);
  y=center.getY() + (int)(Math.sin(a)*distance);

【讨论】:

    【解决方案2】:

    你需要实现二维空间的affine trnsformationexample 是如何使用 java AffineTransform 类实现的。但是如果你不想通过 java Graphics 来做,那么算法分三步:

    1. 将对象置于旋转中心:

      x1=x-centerX;

      y1=y-centerY;

    2. 在角度 alpha 上旋转对象(以弧度为单位):

      x2=x1*Math.cos(alpha)+y1*Math.sin(alpha);

      y2=x1*Math.sin(alpha)-y1.Math.cos(alpha);

    3. 在该位置返回对象:

      x3=x2+centerX;

      y3=y2+centerY;

    这个操作可以简单地转换成矩阵,然后你可以使用矩阵代数来达到你的目的。

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多