I’m doing a 2D game and I need to change the orthographicsize and the position when the player touches a trigger. I have this script, and it works correctly but the zoom is too hard, how can I do smoothly? some idea?
using UnityEngine;
using System.Collections;
public class CameraZoom : MonoBehaviour {
public float ZoomPre;
public float ZoomIdle;
public float duration;
public float ypos1;
public float ypos2;
void Start () {
Camera.main.orthographic = true;
}
void OnTriggerEnter(Collider other) {
if(other.name == "Player"){
Camera.main.orthographicSize = Mathf.Lerp(ZoomPre, ZoomIdle, duration);
Camera.main.GetComponent<CameraMovement>().ypos = Mathf.Lerp(ypos1, ypos2, duration);
}
}
}
Thank you so much, I’m a beginner
Your current code seems to be adjusting the camera in a single frame (OnTriggerEnter()
), I’m not sure what your value of duration is but you are missusing Lerp if you wish to progress from one value to another.
For your needs it is best to have the trigger set in motion a transition that occurs over multiple frames.
Please look at this example (typed without IDE, may contain typos):
using UnityEngine;
using System.Collections;
public class CameraZoom : MonoBehaviour {
public float Zoom1;
public float Zoom2;
public float ypos1;
public float ypos2;
public float duration = 1.0f;
private float elapsed = 0.0f;
private bool transition = false;
void Start () {
Camera.main.orthographic = true;
}
void Update() {
if (transition) {
elapsed += Time.deltaTime / duration;
Camera.main.orthographicSize = Mathf.Lerp(Zoom1, Zoom2, elapsed);
//this next line i'm not sure of, I'm not familiar with CameraMovement.ypos
Camera.main.GetComponent<CameraMovement>().ypos = Mathf.Lerp(ypos1, ypos2, elapsed);
if (elapsed > 1.0f) {
transition = false;
}
}
}
void OnTriggerEnter(Collider other) {
if(other.name == "Player"){
transition = true;
elapsed = 0.0f;
}
}
}
Once you are confident implementing the transition you may want to try substituting Lerp with Mathf.SmoothStep()
. Rather than move at a linear rate, as Lerp does, SmoothStep will accelerate and decelerate at the ends. This results in a more natural looking movement. A graph can be found over here.
Also note that the trigger scripts and the camera management scripts should really be separated. The Point Of Interest should ask (not force) the camera to look at it, otherwise how will you handle the conflict when two POIs are active?
you can use that damping also if you want it to slowly enter and slowly exit so the speed isn’t uniform the whole time use slerp instead of lerp
lerp is linear interpolation each “step” goes the exact same distance
slerp is spherical each “step” is not the same.
check up on wiki if you want a better understanding or google lerp vs slerp.