如何使用360度旋转在2D中获得正确的方向

时间:2014-05-01 13:31:36

标签: java math

我试图让对象的最近方向旋转太快或太短。

基本上,我们的想法是给对象一个理想的方向,并且必须以最短的方式向该方向旋转。

我有以下代码:

rotationChangeAmount = (this.getDirection(getRotation(), mDestinationRotation)) ? -rotationChangeAmount : rotationChangeAmount;

使用以下功能:

private boolean getDirection(double targetRotation, double value)
{
    //Max 100 max (360)
    //Target 60
    //Value 30
    //Value - Max > Target - Max

    if(Math.abs(targetRotation - 360.0) > Math.abs(value - 360.0))
    {
        return false;
    }
    return true;
}

2 个答案:

答案 0 :(得分:3)

逻辑思考,如果值与目标Rotation之间的距离大于180,则顺时针方向,如果小于,则逆时针方向,假设目标<&lt;原始

说我最初有270个,我想要180. abs(270-180)是90,所以我将逆时针旋转,我们从粗略的看起来是正确的。

如果我最初有270并且我想要45,那么(270-45)= 225,所以我会顺时针旋转(我们也知道这是正确的)135度

如果我最初有45,而我想要300,那么abs(45 - 300)= 255,所以我会逆时针旋转(因为初始值小于目标值)105度。

最后,如果我最初有45,我想要90,那么abs(45 - 90)= 45,我会顺时针旋转45度。

所以,要在这个逻辑上构建你的函数:

 private double getChange(double target, double original){
      if (target < original){
           if (Math.abs(original - target) > 180)
               return Math.abs((360 - original) + target);
           else
               return (-1 * Math.abs(target - original);
      }
      else{
           if (Math.abs(target - original) > 180)
               return Math.abs( (360 - target) + original);
           else
               return (-1 * Math.abs(original - target);
      }
 }

答案 1 :(得分:2)

通过TDD完成:

package rotation;

import static org.junit.Assert.*;
import org.junit.Test;

public class RotationTest {
    public enum Direction { RIGHT, LEFT, EITHER }

    public Direction getDirection(double current, double target) {
        validate(current);
        validate(target);
        double alwaysLarger = current < target ? (current + 360) : current;
        double gap = alwaysLarger - target;
        return gap > 180
            ? Direction.RIGHT
            : (gap == 180 ? Direction.EITHER : Direction.LEFT);
    }

    private void validate(double degrees) {
        if (degrees < 0 || degrees > 360) {
            throw new IllegalStateException();
        }
    }

    @Test
    public void test() {
        assertEquals(Direction.LEFT, getDirection(90, 1));
        assertEquals(Direction.LEFT, getDirection(90, 359));
        assertEquals(Direction.LEFT, getDirection(90, 271));
        assertEquals(Direction.EITHER, getDirection(90, 270));
        assertEquals(Direction.RIGHT, getDirection(90, 269));
        assertEquals(Direction.RIGHT, getDirection(90, 180));
    }
}