【问题标题】:Snap to angle if number is within a threshold如果数字在阈值内,则对齐角度
【发布时间】:2019-12-21 02:13:07
【问题描述】:

我想知道什么是检查角度是否在特定角度的特定阈值内的简单方法。

说 45 度,我目前可以得到 45 度的精确倍数,但我希望两边 10 度的余量也适用于整个 360 度圆。但不确定一种干净的方法。

这是我目前拥有的:

float angle = Vector3.SignedAngle(currentGrid.Vector3,Vector3.right, Vector3.up); //[-180,180]
angle += 360;
angle %= 360; //[0,360]
int angle2 = (int)(Mathf.RoundToInt(angle / 5f) * 5f); //snap to nearest 5 degrees

if (angle2 % 45 == 0 || /*angle is within threshold of a multiple of 45 degrees*/ ){
   print("Hello");
}

有没有办法做到这一点,而不需要对每 45 度角进行大量 if 检查?

【问题讨论】:

    标签: c# math


    【解决方案1】:

    您可以使用与 5° 相同的方式进行操作:

    var closest45 = (int)(Mathf.RoundToInt(angle2 / 45f) * 45f);
    if(Math.Abs(closest45 - angle2) < 10) //allow a 10° tolerance to either side
        angle2 = closest45;
    

    【讨论】:

    • 嗯,由于某种原因,它似乎只在矢量的一侧起作用,请参见此处:imgur.com/7ONE77A 当它足够接近时它是绿色的,但在线的另一侧它现在总是红色很重要你有多接近。
    • 您查看过代码中的数字吗? Math.Abs() 应该使它对双方都有效。
    • 啊,是的,我的代码出错了。谢谢。现在工作:)
    猜你喜欢
    • 2011-09-30
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2011-11-30
    • 1970-01-01
    • 2014-08-05
    • 2018-12-13
    相关资源
    最近更新 更多