input.touch拖动物体

using UnityEngine;
using System.Collections;

public class FollowCube : MonoBehaviour
{
//用于绑定参照物对象
public Transform target;
//缩放限制的系数
private float minVertical = 0f;
private float maxVertical = 85f;
//摄像头的位置
private float x = 0.0f;
private float y = 0.0f;
//缩放系数
private float distance = 0.0f;
//记录上一次用户触摸的位置判断用户是放大还是缩小的手势
private float newdis = 0;
private float olddis = 0;
// Use this for initialization
void Start()
{//初始化数据
distance = (transform.position - target.position).magnitude;
}

// Update is called once per frame

void Update()
{ //初始化游戏信息设置
//每帧旋转摄像机,使它保持注视目标
transform.LookAt(target);
//一秒来计算,一帧完成的时间
float dt = Time.deltaTime;
//绕世界坐标旋转的角度
x = transform.eulerAngles.y;
y = transform.eulerAngles.x;

if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
//判断是否是单点触摸
if (Input.touchCount == 1)
{//判断是是类型为移动触摸
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{ //根据触摸点计算x和y的位置,然后重置位置
//target.transform.Translate(Vector3.forward * Time.deltaTime * 5);
//target.transform.LookAt(target.position);
float x1 = Input.GetAxis("Mouse X");
float y1 = Input.GetAxis("Mouse Y");
x += x1 * dt * 150;
y += -y1 * dt * 150;
SetPos(x, y);

}
}
//判断为2点触摸
if (Input.touchCount == 2)
{//判断触摸的类型是这两个点移动触摸
if (Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved)
{//根据两个点的位置重新设置生成新的触摸点的位置
Vector3 s1 = Input.GetTouch(0).position;
Vector3 s2 = Input.GetTouch(1).position;
newdis = Vector2.Distance(s1, s2);
//判断新生成的位置是否大于原始的位置,函数返回真是为放大手势,假为缩小手势
if (newdis > olddis)
{
distance -= Time.deltaTime * 50f;
}
if (newdis < olddis)
{
distance += Time.deltaTime * 50f;
}
//备份上一次触摸点的位置,用于对比
print("distance = " + distance);
SetPos(x, y);
olddis = newdis;

}
}

}
else
{//判断鼠标是否为左键点击。函数返回真旋转
if (Input.GetMouseButton(0))
{

float x1 = Input.GetAxis("Mouse X");
float y1 = Input.GetAxis("Mouse Y");
x += x1 * dt * 150f;
y += -y1 * dt * 150f;
SetPos(x, y);

}

if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
distance -= Input.GetAxis("Mouse ScrollWheel");
SetPos(x, y);
}
}

}


void SetPos(float x, float y)
{
y = ClampAngle(y, minVertical, maxVertical);
var rotation = Quaternion.Euler(y, x, 0.0f);
var position = rotation * new Vector3(0.0f, 0.0f, -distance) + 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);
}

}

posted @ 2016-06-27 09:32  Fei非非  阅读(589)  评论(0编辑  收藏  举报