快速解释代码行

本文关键字:代码 解释 | 更新日期: 2023-09-27 18:08:34

motion *= (Mathf.Abs(inputVec.x) == 1)?.7f:1;

据我所知,这条线意味着,可变运动乘以向量inputVec的x部分的绝对值,但我不明白接下来会发生什么。

快速解释代码行

如果条件Mathf.Abs(inputVec.x) == 1为真,则motion乘以0.7 f。

问号是条件操作符。这是编写if else语句的一种简洁方式。

For,例如:

if(Mathf.Abs(inputVec.x) == 1)
{
    motion *= .7f;
}
else
{
    motion *= .5f; 
}

等价于:

motion *= (Mathf.Abs(inputVec.x) == 1)?.7f:.5f;

所以你可以写一行代码而不是8行!

  • ?:运算符是if/else运算符的简称,称为条件运算符

  • *=操作符是x = x * 1的快捷方式,在这里解释

  • Math.Abs()返回给定值的绝对值

  • 0.7ff是一个后缀,声明值为float类型

.

motion *= (Mathf.Abs(inputVec.x) == 1)?.7f:1;

=

if (Mathf.Abs(inputVec.x) == 1)) //if inputVec.x equals 1 or -1
{
    motion = motion * 0.7;
}
else
{
    motion = motion * 1;
}