- Home /
2D camera zoom smoothing and limitations?
I have a working zoom function for my top down 2D game:
using UnityEngine;
using System.Collections;
public class ZoomFunction : MonoBehaviour {
public float zoomSpeed = 20;
void Update () {
float scroll = Input.GetAxis ("Mouse ScrollWheel");
if (scroll != 0.0f)
{
Camera.main.orthographicSize -= scroll * zoomSpeed;
}
}
}
It works but it jumps in and out rather than being a smooth transition and I would like to set limitations to how far in or out the player can zoom. Any help/advice would be appreciated.
Comment
Answer by robertbu · Nov 16, 2014 at 10:50 PM
Use Mathf.Lerp() or Mathf.MoveTowards():
using UnityEngine;
using System.Collections;
public class ZoomFunction : MonoBehaviour {
public float zoomSpeed = 1;
public float targetOrtho;
public float smoothSpeed = 2.0f;
public float minOrtho = 1.0f;
public float maxOrtho = 20.0f;
void Start() {
targetOrtho = Camera.main.orthographicSize;
}
void Update () {
float scroll = Input.GetAxis ("Mouse ScrollWheel");
if (scroll != 0.0f) {
targetOrtho -= scroll * zoomSpeed;
targetOrtho = Mathf.Clamp (targetOrtho, minOrtho, maxOrtho);
}
Camera.main.orthographicSize = Mathf.MoveTowards (Camera.main.orthographicSize, targetOrtho, smoothSpeed * Time.deltaTime);
}
}