简体   繁体   中英

How to access the main Camera in Unity to make a zoom script?

I am trying to make a simple zoom script for when you click on a cube. I want it to zoom in on the cube, but I cannot find a way to make the main camera zoom for me. I have tried several different ways. Here is the current one. I had it in a OnMouseDown , but it still would not work, so I moved it to update to see if I could get it to work.

void Update ()
{
  if(Input.GetKeyDown("z"))
  {
    Debug.Log("Pressed Z");
    zoomedIn = !zoomedIn;
  }

  if(zoomedIn == true)
  {
      Debug.Log("True!");
      Camera.main.GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime*smooth);
  }
  else
  {
     Camera.main.GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime*smooth);
  }
}

Looks like zoom and normal are not assigned to the correct values. Also make sure that you're in Perspective , not Orthographic view.

If you want to use Orthographic view just change all usages of fieldOfView to orthographicSize and change zoom to something reasonable, like 5 units.

normal should be the initial fieldOfView of the camera, retrieved in Start :

// camera is a private field
private Camera camera;
camera = GetComponent<Camera>();
normal = camera.fieldOfView;

zoom should be a value less than normal (initial fieldOfView ) assigned from the inspector to be able to "zoom in".

Your conditional branch will change to

if (zoomedIn) // Same as if (zoomedIn == true)
{
    camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, zoom, Time.deltaTime * smooth);
}
else
{
    camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, normal, Time.deltaTime * smooth);
}

Or, a more concise version:

camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, zoomedIn ? zoom : normal, Time.deltaTime * smooth);

I also suggest using a Coroutine to do this instead of doing this in Update .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM