20 != 20 怎么能返回真 [英] How can 20 != 20 return true
问题描述
所以,我试图在统一中做一些事情,我写了这样的东西
So, I was trying to do some stuff in unity and i wrote something like this
private IEnumerator RotateToNormal()
{
while (hingePoint.eulerAngles.z > 20)
{
float d = Time.deltaTime * 500;
hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0, Mathf.Clamp(hingePoint.eulerAngles.z - d, 20, 90));
transform.position = hingePoint.position + hingePoint.rotation * new Vector3(camDist, lift, 0);
transform.LookAt(hingePoint);
Debug.Log(hingePoint.eulerAngles.z);
yield return null;
}
inSelection = false;
}
如您所见,它应该从 while() 循环中退出,作为变量等于 20 并达到 20(Debug.Log 和调试器显示,hingePoint.eulerAngles.z = 20)
但是,当它等于 20 时,它不会退出 while() 循环我试图更改运算符(到!=),类型,我在循环中尝试了一些 if 语句,显然它不起作用.有趣的是几乎相同的代码块工作得很好
As you can see, it should bail out from while() loop as variable equal to 20 and it reaches 20(Debug.Log and debugger shows that in hingePoint.eulerAngles.z = 20)
However, when it becomes equal to 20 it does not quit while() loop
I was trying to change operators(to !=), types, I tried some if statements in loop, and apparently it didn't work.
Interesting that almost same code block works just fine
private IEnumerator RotateToTop()
{
inSelection = true;
while (hingePoint.eulerAngles.z < 90)
{
float d = Time.deltaTime * 500;
hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0, Mathf.Clamp(hingePoint.eulerAngles.z + d, 0, 90));
transform.position = hingePoint.position + hingePoint.rotation * new Vector3(camDist, lift, 0);
transform.LookAt(hingePoint);
yield return null;
}
}
所以,由于某种原因,我认为程序认为变量在等于 20 时不等于 20,问题是:怎么可能?
So, as I figured for some reason program thinks that variable is not equal to 20 when it is equal to 20, and there's the question: How can that be?
推荐答案
使用 Mathf.Approximately
当比较浮点数并且您希望它们等于或接近等于某个其他值时:
Use Mathf.Approximately
when comparing floats and you expect them to be equal or nearly equal to some other value:
private IEnumerator RotateToNormal()
{
while (!Mathf.Approximately(hingePoint.eulerAngles.z, 20.0f))
{
float d = Time.deltaTime * 500;
hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0,
Mathf.Clamp(hingePoint.eulerAngles.z - d, 20, 90));
transform.position = hingePoint.position + hingePoint.rotation
* new Vector3(camDist, lift, 0);
transform.LookAt(hingePoint);
Debug.Log(hingePoint.eulerAngles.z);
yield return null;
}
inSelection = false;
}
这篇关于20 != 20 怎么能返回真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!