- Home /
C# please explain this line of code
moveDirection = new Vector3((Input.GetMouseButton(1)
? Input.GetAxis("Horizontal") : 0),0,Input.GetAxis("Vertical"));
Found the MSDN ? operator page but I don't get this one. Input.GetMouseButton(1) is the boolean test clause and ?/if it's true then do Input.GetAxis("Hori... but if it's false (:) then do other stuff. It's the 2nd part I don't get. What's the 0),0 right after the : doing?
Answer by whydoidoit · Sep 05, 2013 at 05:13 AM
So that says:
Create a movement vector that uses the Horizontal axis only if the right mouse button is down and is 0 otherwise, and the Vertical axis always.
The x component of the Vector3 is the GetAxis("Horizontal") if the GetMouseButton(1) is held and is 0 otherwise. The other two components of the Vector3 are the same in all cases.
If right.mouse is held, result is:
new Vector3((Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
or if right.mouse is not/otherwise, result is:
new Vector3((0,0,Input.GetAxis("Vertical"));
Do I have that right? I've seen a few examples of the ?: (thanks PeterG did not know what to call that) but usually to do straight if/then/else logic, this seemed different and I didn't understand. I think I do now. It's elegant, but unfamiliar at first.
Yes, that's correct. The ?: notation is called ternary operator by the way.
condition ? true : false
Answer by Peter G · Sep 05, 2013 at 05:17 AM
It's because whoever wrote the code is writing it into a Vector3. The ?:
(It's called the conditional/ternary operator) is setting the x value of the Vector3. Then the y component is 0, and the z is the other axis.
It would probably make more sense written like this:
moveDirection = new Vector3( Input.GetMouseButton(1) ? Input.GetAxis("Horizontal") : 0 //x
,0 //y
,Input.GetAxis("Vertical") ); //z
There was also an extra set of ()
's.