-1

I was searching to find how to make the camera fit a game object and I found this answer:

Change the size of camera to fit a GameObject in Unity/C# , and I don't understand this part

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

I want to understand how that part of the code works.

  • 1
    Is there anything about that statement you understand? What part do you need explained? Is it the [ternary operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator) that's confusing you? `condition ? A : B` – Wyck Dec 02 '22 at 17:48
  • 1
    Are you just asking what the [ternary conditional operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator) is? – David Dec 02 '22 at 17:50

2 Answers2

1

if you dont understand condition ? A : B

maybe this will help you

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

It's just a matter of breaking it down piece by piece. Let's see:

cam.orthographicSize =

STEP 1: ((w > h * cam.aspect) ? (float)w / (float)cam.pixelWidth * cam.pixelHeight : h)

STEP 2: [STEP 1] / 2

Step 1 divides into the following:

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: Ternary operator (it's just an IF else written in a fancy way)

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

At the end whatever comes from step 1, is divided in 2 (step 2). Here's more info about the ternary operator

mrbitzilla
  • 368
  • 3
  • 11