为什么当play.x的值肯定是1或-1时,if语句没有被读取?
如果您还需要知道任何其他帮助,我将不胜感激,我会尽力解释它。
public class WhyDosntThisWork : MonoBehaviour
{
public bool North = false;
public bool South = false;
public bool West = false;
public bool East = false;
public bool jimmy = false;
public float x = 0;
public float y = 0;
public bool IsRotating = false;
public Vector3 Player;
public float if0trueifnotfalse = 0;
void Start()
{
//Player = transform.up;// tryed here aswell still no work
}
void Update()
{
Player = transform.up;
y = Input.GetAxisRaw("Vertical");// press arrowkey
x = Input.GetAxisRaw("Horizontal");// press arrowkey
print(" y = " + y);
print(" x = " + x);
if (y == 0)
{
WereAreWeLooking();// run function should work???
print("we are Running the Script");
}
if (y > 0)
{
print("We Presed up player.x is now 1");
transform.eulerAngles = new Vector3(0,0,-90); // this changes player.x from -1 to 1
}
if (y < 0)
{
print("We Presed down player.x is now -1");
// WereAreWeLooking();
transform.eulerAngles = new Vector3(0,0,90); //this changes player.x from 1 to -1
}
}
void WereAreWeLooking()
{
print("HI we are checking for bools Player.x IS " + Player.x + " so why dont we change the bool");
if (Player.x == -1)// this never runs even tho play.x is -1
{
print("We Are GoingUp");
North = true;
South = false;
East = false;
West = false;
}
else if (Player.x == 1)
{
print("We Are GoingDown");
South = true;
North = false;
East = false;
West = false;
}
else if (Player.z == 1)
{
print("We Are going East");
East = true;
South = false;
North = false;
West = false;
}
else if (Player.z == -1)
{
print("We Aregoing west");
West = true;
East = false;
South = false;
North = false;
}
print("Thanks Checking done");
jimmy = true;
if (if0trueifnotfalse == 1)// this works if i change the value in the inspector
{
jimmy = false;
print("jimmy is 1");
}
}
}
您正在通过相等运算符比较浮点数。
如果计算了该值,则该值很有可能不会完全是 1 或 -1。例如,它将是1.0000000001
或0.9999999999
。
这意味着您的测试如下所示:
if (Player.x == -1)
总是会失败。
您需要在测试中引入舍入:
if (Player.x + 1 < 10e-6)
这将检查Player.x
是否等于 -1 到 6 位小数,因此 -0.999999
和 -1.000001
将通过测试。您可能需要调整 epsilon 值才能获得稳定的数据解决方案。
当您使用Unity时,您可以使用其内置功能Mathf.Approximately
:
if (Mathf.Approximately(Player.x, -1.0f))
即使您使用double
您仍然会收到这些舍入误差 - 尽管大大减少了。 可能是这样,您使用任何检查值的内容都在执行一些舍入,因此看起来值为 -1 或 1。