Unity鼠标自由查看3D物体之控制摄相机Camera

来源:互联网 发布:js闭包是什么 编辑:程序博客网 时间:2024/05/18 00:30

这种方式是通过控制相机的旋转,位置来查看物体。

下面的代码是通过修改官方的MouseOrbit代码产生,加了缩放功能,以及缩放,旋转,位移的缓动,让它不再那么生硬。

需要将下面的代码放到相机上面。

using UnityEngine;using System.Collections;public class MouseOrbitImproved : MonoBehaviour {public Transform target;public float distance = 8.0f;public float xSpeed = 70.0f;public float ySpeed = 50.0f;public float yMinLimit = 0f;public float yMaxLimit = 90f;public float distanceMin = 8f;public float distanceMax = 15f;public float zoomSpeed=0.5f;private Rigidbody rigidbody;private float x = 0.0f;private float y = 0.0f;private float fx=0f;private float fy=0f;private float fDistance=0;// Use this for initializationvoid Start () {Vector3 angles = transform.eulerAngles;x = angles.y;y = angles.x;fx = x;fy = y;rigidbody = GetComponent<Rigidbody>();// Make the rigid body not change rotationif (rigidbody != null){rigidbody.freezeRotation = true;}UpdateRotaAndPos ();fDistance = distance;}void Update(){// If there are two touches on the device...if (Input.touchCount == 2) {// Store both touches.Touch touchZero = Input.GetTouch (0);Touch touchOne = Input.GetTouch (1);// Find the position in the previous frame of each touch.Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;// Find the magnitude of the vector (the distance) between the touches in each frame.float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;// Find the difference in the distances between each frame.float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;fDistance = Mathf.Clamp ( distance+ deltaMagnitudeDiff * zoomSpeed , distanceMin, distanceMax);}distance = Mathf.Lerp (distance, fDistance, 0.25f);}void LateUpdate () {if (Input.GetMouseButton(0)&&Input.touchCount<2){if (target) {float dx = Input.GetAxis("Mouse X");float dy = Input.GetAxis("Mouse Y");if (Input.touchCount > 0){dx = Input.touches[0].deltaPosition.x;dy = Input.touches[0].deltaPosition.y;}x += dx * xSpeed  * Time.deltaTime;//*distancey -= dy * ySpeed * Time.deltaTime;y = ClampAngle(y, yMinLimit, yMaxLimit);}}fx = Mathf.Lerp (fx, x, 0.2f);fy = Mathf.Lerp (fy, y, 0.2f);UpdateRotaAndPos ();}void UpdateRotaAndPos(){if (target) {Quaternion rotation = Quaternion.Euler(fy, fx, 0);Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);Vector3 position = rotation * negDistance + target.position;transform.rotation = rotation;transform.position = position;}}public static float ClampAngle(float angle, float min, float max){if (angle < -360F)angle += 360F;if (angle > 360F)angle -= 360F;return Mathf.Clamp(angle, min, max);}}


0 0