- Home /
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));
}
}
Answer by Kaze_Senshi · Mar 17, 2012 at 03:14 AM
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) )
...
Reference: http://unity3d.com/support/documentation/ScriptReference/Mathf.Lerp.html
Answer by simeonradivoev · Mar 17, 2012 at 04:46 AM
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;
}
Your answer
Follow this Question
Related Questions
How to rotate smoothly behind target? 0 Answers
Object disappears when zoom 0 Answers
putting an object's x coordinate to another object 1 Answer