Search Unity

Camera distance based on object size?

Discussion in 'Scripting' started by Corva-Nocta, Oct 16, 2019.

  1. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    Working on a project and not sure if this is possible or what it is called but I figured I would ask after a failed google search for the answer. I have a project with many objects, each of which can be clicked on. When an object is clicked on I want the camera to move over to that object. All the objects will be of a different size so I want the camera to make sure it stops at a dynamic distance from each object based on its size.

    Basically I want to make sure the object fills up the screen by only 66% (or whatever number I want to set it to if I need to change it) is there a way to do this? I've got the movement down pretty easily, but I need a dynamic distance check, rather than a static distance check. Something like if(distance < sizeOfTheObjectInTheScreen)

    I could theoretically manually set up a distance for every object, but that is tedious (I have like 100 different objects) and will be a pain if I add any new objects. Any tips?
     
  2. Giustitia

    Giustitia

    Joined:
    Oct 26, 2015
    Posts:
    113
    The parameters involved hera are the object bounds, the camera FOV to get the distance between the camera and the object. By default, FOV is based on vertical axis, and the FOV value means how many degrees has the camera (i.e. FOV 60 means you see from -30 to 30). Knowing that and having your camera looking at the center of the object, you have a rectangle where the opposite side is bounds.y / 2 and the angle of the camera is FOV/2. Now you can get the distance you have to put the camera doing (Bounds.y / 2) / Mathf.Tan(FOV / 2)



    Hope it helps! :)
     
    Melanzue and glenneroo like this.
  3. Giustitia

    Giustitia

    Joined:
    Oct 26, 2015
    Posts:
    113
    Take in mind 2 things. If your object is wider than higher, you'll have to deal with the aspect ratio of your screen and the height-width relation to ensure that the entire object is in the screen. On the other hand, if you want, for example, to have the object occuping just half of your screen you shuld multiply your object height (bounds.y) * 2 I guess.
     
    glenneroo likes this.
  4. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    Thanks for the advice! I'll look into adding that into my code. Its a bit math heavy but I'm sure I could figure it out.

    Good point on the height/width. I didn't consider that at all. Thankfully I only need width so that keeps things simple, but that is something to keep in mind if the models don't work quite right