C# 统一相机运动
我正在复习这段关于相机运动的代码:C# 统一相机运动,c#,unity3d,camera,C#,Unity3d,Camera,我正在复习这段关于相机运动的代码: using UnityEngine; using System.Collections; public class CamMove : MonoBehaviour { Vector2 mouseLook; Vector2 smoothV; public float sensitivity=5.0f; public float smoothing = 2.0f; GameObject character;
using UnityEngine;
using System.Collections;
public class CamMove : MonoBehaviour {
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity=5.0f;
public float smoothing = 2.0f;
GameObject character;
void Start()
{
//moving left and right
character = this.transform.parent.gameObject;
}
void Update()
{
var md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y")); //mouse movement
md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
character.GetComponent<CharacterController>().transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);
}
}
嗯
甚至对鼠标移动进行了注释。像往常一样,更好的变量名已经可以解释它了。最好叫它mouseDelta
。因此,代码不使用固定的鼠标位置,而是使用自上一帧以来的移动距离。(见附件)
然后 正在放大或缩小此向量。你也可以把它写成
md = new Vector2 (md.x * sensitivity * smoothing, md.y * sensitivity * smoothing);
实际上,这是非常不必要的,因为您可以这样简单地编写:
md *= sensitivity * smoothing;
然后是两个给定位置之间的线性插值,使用
0
和1
之间的某个因子,其中0
将完全是第一个参数,1
完全是第二个参数,否则介于两者之间。例如,系数0.5将导致两个值之间的中心,因此这取决于平滑的给定值
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
同样,这是非常不必要的,因为最好直接使用
但事实上,我不太确定这是否达到了你的预期,因为这不是绝对值,而是你以后在每一帧上添加的东西,所以对它使用Lerp
对我来说没有多大意义。。。我可能会直接使用Lerp
将当前的mouselock
移动到新的目标值
你终于做到了
mouseLook += smoothV;
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
character.GetComponent<CharacterController>().transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);
mouseLook+=smoothV;
如果(mouseLook.y>-40&&mouseLook.y)有疑问,请按照代码进行操作。如果您不了解它的作用,请查找unity调用,打印出值…然后观察并查看发生了什么。当使用鼠标位置调用时,代码所做的只是左右移动相机。它只查看y范围-40到60。
md *= sensitivity * smoothing;
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
smoothV = Vector2.Lerp(smoothV, md, 1f/smoothing);
mouseLook += smoothV;
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
character.GetComponent<CharacterController>().transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);