There are two sets of information that you want to keep track of: the 3rd person camera view, and the “2d” camera view. To switch between these two transforms smoothly, you can use Vector3.Lerp to interpolate the position of the camera and Quaternion.Lerp to interpolate the rotation of the camera.
Let’s refer to the camera position/rotations as camPos3d, camRot3d, camPos2d, camRot2d
. Inside your LateUpdate
, you would do something along the lines of this (pseudocode):
camera.transform.position = Vector3.Lerp(camPos3d, camPos2d, t);
camera.transform.rotation = Quaternion.Lerp(camRot3d, camRot2d, t);
Here t
is a float value between 0 and 1. If t
is 0, the camera position will be in the 3rd person view. If t
is 1, the camera will be in 2d view. If t
is somewhere in between, the camera will be in a position somewhere in between.
What you can do now is in your collision handling code, if you’re colliding with the right thing, increase t
gradually. If you’re not colliding with the right thing, decrease t
gradually, clamping at 0/1.
Basic Example Code (C#)
using UnityEngine;
using System.Collections;
public class SmoothCameraSwapExample : MonoBehaviour {
private GameObject mainCamera;
private GameObject dummyCameraA;
private GameObject dummyCameraB;
private float cameraLerpAmount;
void Start () {
mainCamera = GameObject.FindGameObjectWithTag ("MainCamera");
// The dummy cameras are empty game objects used to keep track of the camera positions
dummyCameraA = new GameObject ("Dummy Camera A");
dummyCameraB = new GameObject ("Dummy Camera B");
dummyCameraA.transform.SetParent (transform);
dummyCameraB.transform.SetParent (transform);
dummyCameraA.transform.localPosition = new Vector3 (10, 5, 0);
dummyCameraB.transform.localPosition = new Vector3 (4, 0, -4);
dummyCameraA.transform.LookAt (transform);
dummyCameraB.transform.LookAt (transform);
}
void Update () {
// Space switches between the two camera positions
if (Input.GetKey (KeyCode.Space)) {
cameraLerpAmount = Mathf.Clamp01 (cameraLerpAmount + 0.1f);
} else {
cameraLerpAmount = Mathf.Clamp01 (cameraLerpAmount - 0.1f);
}
}
void LateUpdate() {
mainCamera.transform.position = Vector3.Lerp (dummyCameraA.transform.position, dummyCameraB.transform.position, cameraLerpAmount);
mainCamera.transform.rotation = Quaternion.Lerp (dummyCameraA.transform.rotation, dummyCameraB.transform.rotation, cameraLerpAmount);
}
}
This should be the basics of what you want. Just attach it to a GameObject and press space to swap views. The positions are currently hard-coded, but I think you’ll get the idea. (Also, you need a camera tagged “MainCamera” in your scene.) Feel free to ask for more clarification.