您的位置:首页 > 移动开发 > Unity3D

Unity 相机 2D视角 与3D 视角 自由动态 切换

2017-12-21 09:41 756 查看

再游戏运行的时候,往往需要 在
正交Orthographic (无消失点投影)
正交Orthographic (无消失点投影)
两个视角中来回转化。 以达到 不同的 2D 与 3D 视角。

So! 今天的 实例代码就是 描述了 这一个功能:

using UnityEngine;

public enum Views
{
_2DView = 1,
_3DView
}
public class BackupCameraProjectionChange
{
/// <summary>
/// 相机透视改变是否触发(调用只需把此值改为true)
/// </summary>
public bool ChangeProjection = false;
private bool _changing = false;
private float ProjectionChangeTime = 0.5f;
private float _currentT = 0.0f;
private Camera m_Camera;

protected Views cur_Views = Views._3DView;

public Views GetCurViews
{
get
{
return cur_Views;
}
}

public BackupCameraProjectionChange(Camera camera = null , float speed = 0.5f)
{
ProjectionChangeTime = speed;
if (m_Camera == null && camera == null)
{
m_Camera = Camera.main;
}
else
{
m_Camera = camera;
}
}

///这个 Update 需要在 其他继承自 MonoBehaviour 类的 Update 中 调用
public void Update()
{
if (m_Camera == null)
return;

if (_changing)
{
ChangeProjection = false;
}
else if (ChangeProjection)
{
_changing = true;
_currentT = 0.0f;
}

LateUpdate();
}

void LateUpdate()
{
if (!_changing)
{
return;
}
//将当前的 是否正视图值 赋值给currentlyOrthographic变量
bool currentlyOrthographic = m_Camera.orthographic;

//定义变量存放当前摄像机的透视和正视矩阵信息;
Matrix4x4 orthoMat, persMat;
if (currentlyOrthographic)//如果当前摄像机为正视状态,则切换为3D
{
orthoMat = m_Camera.projectionMatrix; //保留 2D矩阵信息

m_Camera.orthographic = false;  //为 3D
m_Camera.ResetProjectionMatrix();
persMat = m_Camera.projectionMatrix;   //保留 3D 矩阵信息

cur_Views = Views._3DView;
}
else//否则当前摄像机为透视状态, 则切换为2D
{
persMat = m_Camera.projectionMatrix; //保留 3D 矩阵信息

m_Camera.orthographic = true;    //为2D
m_Camera.ResetProjectionMatrix();
orthoMat = m_Camera.projectionMatrix;  //保留 2D矩阵信息

cur_Views = Views._2DView;
}
m_Camera.orthographic = currentlyOrthographic;

_currentT += (Time.deltaTime / ProjectionChangeTime);
if (_currentT < 1.0f)
{
if (currentlyOrthographic)
{
m_Camera.projectionMatrix = MatrixLerp(orthoMat, persMat, _currentT * _currentT);  //从2D 到 3D
}
else
{
m_Camera.projectionMatrix = MatrixLerp(persMat, orthoMat, Mathf.Sqrt(_currentT)); //从3D 到 2D
}
}
else

4000
{
_changing = false;
m_Camera.orthographic = !currentlyOrthographic;  //取反
m_Camera.ResetProjectionMatrix();   // 重置
}
}

private Matrix4x4 MatrixLerp(Matrix4x4 from, Matrix4x4 to, float t)
{
t = Mathf.Clamp(t, 0.0f, 1.0f);
Matrix4x4 newMatrix = new Matrix4x4();
newMatrix.SetRow(0, Vector4.Lerp(from.GetRow(0), to.GetRow(0), t));
newMatrix.SetRow(1, Vector4.Lerp(from.GetRow(1), to.GetRow(1), t));
newMatrix.SetRow(2, Vector4.Lerp(from.GetRow(2), to.GetRow(2), t));
newMatrix.SetRow(3, Vector4.Lerp(from.GetRow(3), to.GetRow(3), t));
return newMatrix;
}
}


更多: Unity 算法功能 日記

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: