ARPG游戏摄像机视野控制脚本---光标、旋转、缓动等效果代码:
using UnityEngine;
using System.Collections;
//自由旋转相机视角
//脚本绑定A空对象,A空对象在角色脚底,A空对象绑定一个B空对象,B空对象绑定一个摄像机
public class FreeLookCamPractice : AbstractTargetFollowerPractice
{
[SerializeField] private float moveSpeed = 1; //移动速度
[Range(0, 10)]
[SerializeField] private float TurnSpeed = 5.5f; //转动速度
[SerializeField] private float TurnSmoothing = 0.1f; //转动平滑值
[SerializeField] private float tiltMax = 75; //倾斜最大值
[SerializeField] private float tiltMin = 45; //倾斜最小值
public bool lookCursor = false; //隐藏锁定光标
private float lookAngle; //看的角度 左右
private float tiltAngle; //倾斜角度 上下
private Transform pivot; //枢轴中心点
private PersonCharacters character; //脚本引用
private const float LookDistance = 100; //看的距离
private float smoothX = 0; //平滑X
private float smoothY = 0; //平滑Y
private float smoothXvelocity = 0; //平滑X速率
private float smoothYvelocity = 0; //平滑Y速率
void Awake()
{
pivot = transform.GetChild (0); //脚本绑定的游戏物体子对象是枢轴中心,应该在人物头顶 枢轴中心的子对象是相机
}
void Update()
{
HandleRotationMovement ();
}
protected override void FollowTarget(float deltaTime)
{
//插值 脚本位置,玩家位置,time.deltaTime * 1
//第三参数是0时返回transform.position,1时返回target.position,0.5返回平均数
transform.position = Vector3.Lerp (transform.position, target.position, deltaTime * moveSpeed);
}
void HandleRotationMovement ()
{
float x = Input.GetAxis ("Mouse X"); //跨平台输入,需要包含脚本,不然就换Input
//启用垂直方向的视野改变
//float y = Input.GetAxis ("Mouse Y");
//取消垂直方向的视野改变
float y = 0f;
if (TurnSmoothing > 0) //如果使用平滑
{
smoothX = Mathf.SmoothDamp (smoothX, x, ref smoothXvelocity, TurnSmoothing); //平滑阻尼,左右移动平滑,TurnSmoothing是缓冲时间
smoothY = Mathf.SmoothDamp (smoothY, y, ref smoothYvelocity, TurnSmoothing); //平滑阻尼,上下移动平滑,TurnSmoothing是缓冲时间
}
else
{
smoothX = x;
smoothY = y;
}
lookAngle += smoothX * TurnSpeed; //Y旋转,左右的,每帧加一点
transform.rotation = Quaternion.Euler (0, lookAngle, 0); //转换成欧拉角才能赋值给rotation
tiltAngle -= smoothY * TurnSpeed; //用减是因为,鼠标向下是是小于0的值,但向上是要加的
tiltAngle = Mathf.Clamp (tiltAngle, -tiltMin, tiltMax);
//旋转B子对象是因为视角要对齐到头顶
pivot.localRotation = Quaternion.Euler (tiltAngle, 0, 0);
Screen.lockCursor = lookCursor; //锁定或解锁光标
}
}