当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");
}
}
}
答案 0 :(得分:3)
您正在通过相等运算符比较浮点数。
如果计算出该值,则很有可能该值将不完全是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。