unity3d 有人能给我解释一下这个语法的意思吗?[duplicate]

ztigrdn8  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(128)

此问题在此处已有答案

How does the ternary operator work?(12个答案)
昨天关门了。
我正在寻找如何使相机适合游戏对象,我发现了这个答案:
Change the size of camera to fit a GameObject in Unity/C#,我不明白这部分

cam.orthographicSize = ((w > h * cam.aspect) ? (float)w / (float)cam.pixelWidth * cam.pixelHeight : h) / 2;

我想知道那部分代码是如何工作的。

erhoui1w

erhoui1w1#

如果你不理解condition ? A : B
也许这个能帮到你

if(w > h * cam.aspect){
  cam.orthographicSize = ((float)w / (float)cam.pixelWidth * cam.pixelHeight ) / 2
}
else{
  cam.orthographicSize = h / 2
}
mspsb9vt

mspsb9vt2#

这只是一个问题,打破它一块一块。让我们看看:
cam.orthographicSize =
STEP 1: ((w > h * cam.aspect) ? (float)w / (float)cam.pixelWidth * cam.pixelHeight : h)
STEP 2: [STEP 1] / 2
步骤1分为以下几个部分:
STEP 1.1: h * cam.aspect (let's call this "JOHN")
STEP 1.2: (float)cam.pixelWidth * cam.pixelHeight (let's call this "WENDY")
STEP 1.3:三元运算符(它只是一个用花哨的方式编写的IF else)

IF w is greater than "JOHN" THEN
    RETURN (float)w / "WENDY"
ELSE
    RETURN h

最后,无论从步骤1得到什么,都被分为2(步骤2)。

相关问题