Search Unity

Repositioning Camera To Have A Certain Width At Z=0 Plane

Discussion in 'Scripting' started by yasirkula, Aug 22, 2014.

  1. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    Hi all,

    I have a camera and it is positioned at (0,0,0). I want to move the camera backwards such that the function Camera.main.ViewportToWorldPoint( new Vector3( 1, 0.5, Camera.main.transform.position.z ) ) will return "almost" exactly 10. In other words, camera's horizontal field of view will be 20-unit wide at the plane Z=0.

    I gave this short script to the camera:

    Code (JavaScript):
    1. function Start()
    2. {
    3.     transform.position.z -= 10 / Mathf.Tan( Mathf.Deg2Rad * camera.fieldOfView * camera.aspect * 0.5f );
    4. }
    5. function Update()
    6. {
    7.     print( camera.ViewportToWorldPoint( new Vector3( 1, 0.5, -transform.position.z ) ) );
    8. }
    It prints 8.5 to the console. My math is not very good but I really expected some value very close to 10. Can someone help me solve my problem?

    Thank you :)
     
  2. yasirkula

    yasirkula

    Joined:
    Aug 1, 2011
    Posts:
    2,879
    OK changing the code like this did the work:

    Code (JavaScript):
    1. transform.position.z -= 10 / ( Mathf.Tan( Mathf.Deg2Rad * camera.fieldOfView * 0.5f ) * camera.aspect );
    Seems like I misunderstood the meaning of the aspect.