using UnityEngine;
using System.Collections;public class TouchRotateTarget : MonoBehaviour {
public Transform target;//绑定参照物 public float distance = 2f;//缩放系数//左右滑动移动速度
public float xSpeed = 250.0f; public float ySpeed = 120.0f;//缩放限制系数
public int yMinLimit = -20; public int yMaxLimit = 80;//摄像头位置
public float x = 0.0f; public float y = 0.0f;//记录上一次手机触摸位置判断用户是放大还是缩小
private Vector2 oldPosition1; private Vector2 oldPosition2;//不让用户触摸操作
public bool TouchBOOL = false;// Use this for initialization
void Start() { Vector3 angles = transform.eulerAngles; x = angles.y; y = angles.x;if (rigidbody)
rigidbody.freezeRotation = true;}
// Update is called once per frame
void Update() { if (TouchBOOL == true) { //判断触摸数量为单点触摸 if (Input.touchCount == 1) { //触摸类型为移动触摸 if (Input.GetTouch(0).phase == TouchPhase.Moved) { //根据触摸点计算X与Y位置 x += Input.GetAxis("Mouse X") * xSpeed * 0.015f; y -= Input.GetAxis("Mouse Y") * xSpeed * 0.015f; } }//判断触摸数量为多点触摸
if (Input.touchCount > 1) { //前两只手指触摸类型都为移动触摸 if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) { //计算当前两点触摸位置 Vector2 tempPosition1 = Input.GetTouch(0).position; Vector2 tempPosition2 = Input.GetTouch(1).position;//函数返回为真放大,返回为假缩小
if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2)) { //放大系数超过3,不允许继续放大 if (distance > 3) { distance -= 0.4f; } } else { //缩小系数小于18.5,不允许缩小 if (distance < 20) { distance += 0.4f; } } //备份上一次触摸的位置,用于对比 oldPosition1 = tempPosition1; oldPosition2 = tempPosition2; } } } } bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2) { //函数传入上一次触摸两点的位置与本次触摸的位置计算出用户手势 float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y)); float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y)); if (leng1 < leng2) { return true; } else { return false; } }void LateUpdate()
{ //target为我们绑定的箱子变量,缩放旋转的参照物 if (target) {//重置摄像机的位置
y = ClampAngle(y, yMinLimit, yMaxLimit); Quaternion rotation = Quaternion.Euler(y, x, 0); Vector3 disVector = new Vector3(0.0f, 0.0f, -distance); Vector3 position = rotation * disVector + target.position;transform.rotation = rotation;
transform.position = position; } }static float ClampAngle(float angle, float min, float max)
{ if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); }}