本文原创,转载请注明出处:http://www.cnblogs.com/AdvancePikachu/p/6555188.html

最近在做一款VR项目,有一个查看功能,分为自由查看和跟随查看。

自由查看:

第一人称自由控制查看。使用firstPersonControl即可。

跟随查看:

摄像机可自由旋转并跟随查看的物体移动(摄像机不可为子物体)。

刚开始使用固定坐标的方法,但摄像机无法自由旋转。后来换用rotatearound,可以自由旋转,可一旦物体移动,旋转半径会拉大。

最后,模仿手势插件写了一个方法,代码如下:

 public Transform target;

     public float minDistance = 1.5f;
public float maxDistance = 10.0f; public float yawSensitivity =30f;
public float pinchSensitivity = 5.0f; public float smoothZoomSpeed = 30.0f;
public float smoothOrbitSpeed = 10.0f; float distance = 5.0f;
float yaw = ;
float pitch = ; float idealDistance = ; bool rotate; public float IdealDistance
{
get { return idealDistance; }
set { idealDistance = Mathf.Clamp( value, minDistance, maxDistance ); }
} public float Yaw
{
get { return yaw; }
} void Start()
{
Vector3 angles = transform.eulerAngles; distance = IdealDistance = 5f;
yaw = angles.y;
pitch = ; UpdateCamera();
} void Update()
{
if (Input.GetMouseButtonDown ())
rotate = true;
if (Input.GetMouseButtonUp ())
rotate = false; if( rotate )
{
yaw += Input.GetAxis ("Mouse X") * yawSensitivity;
pitch -= Input.GetAxis ("Mouse Y") *pinchSensitivity;
} IdealDistance -= Mathf.Lerp (, Input.GetAxis ("Mouse ScrollWheel") * smoothZoomSpeed, Time.deltaTime);
IdealDistance = Mathf.Clamp (IdealDistance, minDistance, maxDistance);
} void LateUpdate()
{
UpdateCamera ();
} void UpdateCamera()
{
distance = Mathf.Lerp (distance, IdealDistance, Time.deltaTime * smoothZoomSpeed); Vector3 lookAtPos = target.position;
Quaternion rotaetAngle = Quaternion.Euler (pitch, yaw, ); Vector3 desiredPos = lookAtPos - rotaetAngle * new Vector3 (, , distance); transform.position = desiredPos;
transform.rotation = rotaetAngle; transform.LookAt (target);
} static float ClampAngle( float angle, float min, float max )
{
if( angle < - )
angle += ; if( angle > )
angle -= ; return Mathf.Clamp( angle, min, max );
}

以上,完美实现摄像机跟随,并可以右键旋转,滚轮拉近功能。

05-11 13:49