簡體   English   中英

如何使用360度旋轉獲得正確的2D方向

[英]How to get the right direction in 2D using 360 rotation

我正在嘗試為物體旋轉得最近或最短的方向。

基本上,該想法是為對象指定所需的方向,並且必須以盡可能短的方式朝該方向旋轉。

我有以下代碼:

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;
}

從邏輯上考慮此問題,如果值和目標Rotation之間的距離大於180,則順時針旋轉;如果較小,則逆時針旋轉,並假設目標<原始。

假設我最初有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);
      }
 }

通過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));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM