标签:
1 using UnityEngine; 2 using System.Collections; 3 4 public class CameraControl : MonoBehaviour { 5 public Transform target; 6 public float distance = 5f;//缩放系数 7 public float mixdistance = 2;//摄像机离物体的最近距离,越小放大倍数越大 8 public float maxdistance = 10;//摄像机离物体的最远距离,越大缩小程度越高 9 10 public float xSpeed = 250.0f; 11 public float ySpeed = 120.0f; 12 13 public float yMinLimit = -80;//角度限制系数 14 public float yMaxLimit = 80; 15 16 public float x = 0.0f;//摄像头的位置 17 public float y = 0.0f; 18 private Vector2 oldPosition1; 19 private Vector2 oldPosition2; 20 // Use this for initialization 21 void Start () { 22 Vector3 angles = transform.eulerAngles; 23 x = angles.y; 24 y = angles.x; 25 //this.transform.position = target.transform.position + new Vector3(0,0,2);//赋予摄像头位置 26 27 // Make the rigid body not change rotation 28 if (GetComponent< Rigidbody >()) 29 GetComponent< Rigidbody >().freezeRotation = true; 30 } 31 32 33 // Update is called once per frame 34 void Update() 35 { 36 if (Input.touchCount == 1) 37 { 38 39 if (Input.GetTouch(0).phase == TouchPhase.Moved) 40 { 41 42 x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; 43 y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; 44 45 } 46 } 47 48 49 if (Input.touchCount > 1) 50 { 51 52 if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) 53 { 54 55 var tempPosition1 = Input.GetTouch(0).position; 56 var tempPosition2 = Input.GetTouch(1).position; 57 if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2)) 58 { 59 if (distance > mixdistance) 60 { 61 distance -= 0.5f; 62 } 63 } 64 else 65 { 66 if (distance < maxdistance) 67 { 68 distance += 0.5f; 69 } 70 } 71 oldPosition1 = tempPosition1; 72 oldPosition2 = tempPosition2; 73 } 74 } 75 } 76 bool isEnlarge(Vector2 oP1, Vector2 oP2,Vector2 nP1, Vector2 nP2) 77 { 78 var leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y)); 79 var leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y)); 80 if(leng1<leng2) 81 { 82 return true; 83 }else 84 { 85 return false; 86 } 87 } 88 void LateUpdate() 89 { 90 if (target) 91 { 92 93 y = ClampAngle(y, yMinLimit, yMaxLimit); 94 var rotation = Quaternion.Euler(y, x, 0); 95 var position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.position; 96 97 transform.rotation = rotation; 98 transform.position = position; 99 } 100 } 101 static float ClampAngle(float angle,float min,float max) 102 { 103 if (angle < -360) 104 angle += 360; 105 if (angle > 360) 106 angle -= 360; 107 return Mathf.Clamp(angle, min, max); 108 } 109 }
参考http://www.xuanyusong.com/archives/512
标签:
原文地址:http://www.cnblogs.com/luxishi/p/5496529.html