Why use the variable distance

hello,

i have a question, why use this part of code:

float distance = transform.position.z - Camera.main.transform.position.z;

i have replaced distance in this part of code(with: 0,10,-10,-100,100):

Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0,0,distance));
Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1,0,distance));

but i don’t see a difference.

I think this might be a tie-in to a previous section where although the game is 2D, your z value will determine rendering order. In this case, it’s possible that z values could be different from object to object and could need to be adjusted for whatever reason while you’re developing. Creating this variable means that this z value is basically going to be maintained, whatever is selected.

This is what I thought when I was going through the exercise.

This is because we are using an orthographic camera in 2D mode.
To explain it better, the code below will lead to two different outcomes depending on the camera type.

Code:

if Camera was orthographic:

if Camera was perspective:

As you can see in case of ortho camera all spheres for 0,0 viewport coordinate will have have the same x,y world coordinate irrespective of the z value supplied to the ViewportToWorld method.
This will not be true if the camera was perspective.

In the case of laser defender and most 2d games( i guess…) the z value would not matter for use with this method.

3 Likes

Privacy & Terms