镜头的缩放和视野控制是3D 游戏中常用的操作,下面是在unity中利用脚本实现这样的功能。
1.镜头的缩放
在操作中使用Lerp()进行平缓的缩放
关于float Mathf.Lerp(float a,float b,float t),我个人的理解是这个函数的返回值是第一个参数a加上参数a与参数b之间距离的t倍,其中t通常是一个小于1的小数。
即Mathf.Lerp(a,b,t) = a+(b-a)*t;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camerLevel : MonoBehaviour
{
//使用前需要在Inspector面板中设置视野缩放的等级。
public float[] leval;//使用时现在面板里进行设置
private int index = 0;
private Camera cameraControl;
public float FOV;
bool changeStatus = false;//判断是否在转化的过程中
float now,last;
void Start()
{
cameraControl = this.GetComponent<Camera>();
}
void Update()
{
if (Input.GetMouseButtonDown(0)&&!changeStatus)
{
index++;
changeStatus = !changeStatus;
now = leval[index % leval.Length];
last = leval[(index - 1) % leval.Length];
cameraControl.fieldOfView = last;
}
if (changeStatus)
{
cameraControl.fieldOfView = Mathf.Lerp(cameraControl.fieldOfView, now = leval[index % leval.Length],0.1f);//
FOV = cameraControl.fieldOfView;
if (Mathf.Abs(FOV - now) <= 1)
{
changeStatus = !changeStatus;
}
}
}
}
2.控制视野的变化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//这个脚本用来利用鼠标控制相机角度的变化
public class cameraControl : MonoBehaviour
{
private Transform cameraTF;
public float x, y;
public float mouseAdd = 50;
void Start()
{
cameraTF = this.transform;
}
// Update is called once per frame
void Update()
{
x = Input.GetAxis("Mouse X");
y = Input.GetAxis("Mouse Y");
x *= rotateSpeed*Time.deltaTime;
y *= rotateSpeed*Time.deltaTime;
cameraTF.Rotate(0,x,0);
cameraTF.Rotate(-y,0,0,Space.World);
}
}
代码中的虚拟按键“Mouse X”,“Mouse Y”是在unity中设置的值,具体步骤是Edit——Project Settings——Input