[英]Why does scroll wheel input only work in the alternate case
我有一系列武器,我正在尝试使用滚轮循环使用它们。 我有代码,但它只会在一次移动(溢出)中从最低索引滚动到最高索引,但它不会通过数组一一计数。 这是我的代码
void Update()
{
var d = Input.GetAxis("Mouse ScrollWheel"); //ScrollWheel Input
if (d > 0f)
{
activeWeaponIndex = (activeWeaponIndex + 1 < weapons.Length) ? activeWeaponIndex++ : activeWeaponIndex = 0; //Increment index, if at max set to 0
}
else if (d < 0f)
{
activeWeaponIndex = (activeWeaponIndex - 1 >= 0) ? activeWeaponIndex-- : activeWeaponIndex = 3; //Increment index unless it is at min then set to 3(4th wep)
}
Swap(activeWeaponIndex); //Switch Weapon
}
您应该确保在分配值之前增加/减少 activeWeaponIndex。 通常做x = x++
不会改变x
的值。 而且您错误地使用了三元运算符。 它应该是:
x = (conditional) ? value1 : value2
你在做:
x = (conditional) ? value1 : statement1
但是,您可以通过赋值语句返回右手侧的值这一事实而得救。
您可以将代码更改为:
void Update()
{
var d = Input.GetAxis("Mouse ScrollWheel"); //ScrollWheel Input
if (d > 0f)
{
activeWeaponIndex = (activeWeaponIndex + 1 < weapons.Length) ? ++activeWeaponIndex : 0; //Increment index, if at max set to 0
}
else if (d < 0f)
{
activeWeaponIndex = (activeWeaponIndex - 1 >= 0) ? --activeWeaponIndex : 3; //Decrement index unless it is at min then set to 3(4th wep)
}
Swap(activeWeaponIndex); //Switch Weapon
}
编辑:在 Draco18snolongertrustsSE 的好评之后,这里是另一个版本:
void Update()
{
var d = Input.GetAxis("Mouse ScrollWheel"); //ScrollWheel Input
if (d==0)
{
return;
}
activeWeaponIndex = (d > 0f) ?
activeWeaponIndex = (activeWeaponIndex + 1) % weapons.Length :
activeWeaponIndex + (weapons.Length-1) % weapons.Length;
Swap(activeWeaponIndex); //Switch Weapon
}
如果d
等于 0,它还可以避免更换武器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.