# Zoom camera based on position between player an object

So I have an object, and I want the camera to zoom in on the player as he walks closer to the object. Also my camera has a variable for distance to player.

Here is my attempt (noob alert)

```
var zoomToBed = true;
var player : Transform;
var mainCamera : Transform;
var zoomDistance = 10.0 ;
private var camDefZoom ;

function OnTriggerEnter (other : Collider){
while(zoomToBed){
yield;
mainCamera.GetComponent(CameraScrolling).distance = camDefZoom - ((15 - 10)*(((this.transform.position.x / player.transform.position.x)*100)/100));
}
}
```

I was thinking something like this that you made. You get the distance between the player and the wall, and use it as a variable between 0 and 1 multiplied by your camera distance. I recommend you to “interpolate” the zoom value instead of just change using the Lerp function, to make it more “smoothly”. The code is something like ( i didn’t test this one ):

``````...
var MaxDistPlayerWall : float = 30.0; /* One value close from the maximum distance between the objects */
var distPlayerWall : float = /*calculate distance*/
var maximumZoom : float = 5.0; /*zzzooomm*/

mainCamera.GetComponent(CameraScrolling).distance = Mathf.Lerp( mainCamera.GetComponent(CameraScrolling).distance, mainCamera.GetComponent(CameraScrolling).distance + ( maximumZoom * (distPlayerWall/MaxDistPlayerWall) )
...
``````

I did it ! You just need to put a object, in my case it was at a wall. Then you need to assign how far from the object the zoom will occur. You might add a if statement so that the zooming will stop when the player is at a specific position, if your object is in the middle of the scene. This is meant for a sidescroller, that’s why i use only the x value.

PS. I don’t know if the code can be more optimized, I would appreciate if someone can optimize it more for multiple uses in a level.

`````` var zoomBoundary = 15;
var zoom = 13;
var player : Transform;
var mainCamera : Transform;
var defZoom;

function Start () {
defZoom = mainCamera.GetComponent(CameraScrolling).distance;
}

function Update () {
if (player.transform.position.x < zoomBoundary)
mainCamera.GetComponent(CameraScrolling).distance = zoom +((defZoom - zoom)*(player.transform.position.x -this.transform.position.x) /(zoomBoundary - this.transform.position.x));

else
mainCamera.GetComponent(CameraScrolling).distance = defZoom;
}
``````