【问题标题】:How to rotate actor using the shortest direction in libgdx, scene2d?如何使用 libgdx、scene2d 中的最短方向旋转演员?
【发布时间】:2023-03-08 20:39:01
【问题描述】:

当我想使用RotateToAction 旋转演员时,例如从 0 度到 300 度,演员旋转 300 度(呃),但同样可以通过逆时针旋转 60 度来实现,这就是我想要的。

如果我使用RotateByAction 并将角度设置为负 60 度,我会得到我的演员的负旋转值,这也不是我想要的。

那么如何使用任一动作将我的演员旋转到某个角度,始终使用最短的旋转并保持 0 到 360 之间的正旋转值?

【问题讨论】:

    标签: java android libgdx


    【解决方案1】:

    您所说的“保持正旋转值”并不完全清楚。如果要将actor旋转到270度,可以执行的最短旋转是-90度。逆时针旋转本质上是负数...

    假设您只想指定一个介于 0 和 360 之间的度数,并让 actor 确定是顺时针还是逆时针旋转,您可以尝试编写你自己的行动。这样的事情怎么样?

    public class MyRotateAction extends Action {
        private Actor actor;
        private int finalDegrees;
    
        public MyRotateAction(Actor actor, int finalDegrees) {
            this.actor = actor;
            this.finalDegrees = finalDegrees;
        }
    
        @Override
        public boolean act(float delta) {
            if (finalDegrees - actor.getRotation() > 180) { //perform negative rotation
                actor.addAction(rotateBy(actor.getRotation() - finalDegrees));
            } else { //perform positive rotation
                actor.addAction(rotateBy(finalDegrees - actor.getRotation());
            }
        }
    }
    

    【讨论】:

    • 当我告诉演员旋转 -90 度然后调用 getRotation() 时,我得到 -90,而我想得到 270,这就是我所说的“保持正旋转值”。问题是,否则我会在某个时候得到 -1000 或 +1000 的值,这使得使用旋转违反直觉。
    【解决方案2】:

    试着让你的演员的角度值在 0 到 360 之间,这会让一切变得更容易,具体取决于游戏:

    float a = actor.getRotation();
    if(a > 360) 
        a -= 360;
    if(a < 0) 
        a += 360;
    actor.setRotation(a);
    

    找到距离演员角度小于或等于 180° 的最接近的角度值,例如:

    float degrees = angle_to_rotate_to;
    float a = actor.getRotation();
    
    if(degrees-a < 180) degrees += 360;
    if(degrees-a > 180) degrees -= 360;
    

    或者,如果您不想将演员角度限制为 0 和 360:

    float degrees = angle_to_rotate_to;
    float a = actor.getRotation();
    while (degrees-a < 180) degrees += 360;
    while (degrees-a > 180) degrees -= 360;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2016-05-28
      • 2013-10-04
      • 1970-01-01
      • 2015-12-10
      • 2012-12-04
      相关资源
      最近更新 更多