using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//两指缩放
public class ZoomControl : MonoBehaviour
{
//旧的触摸点位置
Vector2 oldPos1;
Vector2 oldPos2;
public delegate void ZoomEvent();
public ZoomEvent ZommOutEvent; //放大事件
public ZoomEvent ZommInEvent; //缩小事件
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//判断触摸点的数量是否为两个
if(Input.touchCount == 2)
{
if(Input.GetTouch(0).phase == TouchPhase.Began||Input.GetTouch(1).phase==TouchPhase.Began)
{
oldPos1=Input.GetTouch(0).position;
oldPos2=Input.GetTouch(1).position;
}
//判断两个触摸点的状态是否为手指进行了移动
if (Input.GetTouch(0).phase == TouchPhase.Moved||Input.GetTouch(1).phase==TouchPhase.Moved)
{
//新的触摸点的位置
Vector2 newPos1 = Input.GetTouch(0).position;
Vector2 newPos2 = Input.GetTouch(1).position;
//判断触摸的手势是否为放大
if(isEnLarge (oldPos1,oldPos2,newPos1,newPos2))
{
//缩放事件回调 , 缩放变化值 设置为 0.002f 缩放会比较流畅
if(ZommOutEvent!=null)
{
ZommOutEvent();
}
}
else //如果触摸手势为缩小,同理缩小1.025倍
{
if(ZommInEvent!=null)
{
ZommInEvent();
}
}
//新的位置覆盖旧的位置
oldPos1 = newPos1;
oldPos2 = newPos2;
}//if_end
}//if_end
}
//判断手势是否为放大手势
bool isEnLarge(Vector2 oldP1, Vector2 oldP2,Vector2 newP1,Vector2 newP2)
{
//计算旧两点间的距离与新两点间的距离
float oldLength = Mathf.Sqrt((oldP1.x - oldP2.x) * (oldP1.x - oldP2.x) + (oldP1.y - oldP2.y) * (oldP1.y - oldP2.y));
float newLength = Mathf.Sqrt((newP1.x - newP2.x) * (newP1.x - newP2.x) + (newP1.y - newP2.y) * (newP1.y - newP2.y));
//判断旧两点间的距离与新两点间的距离大小,如果旧的距离小于新的距离,说明是放大手势
if (oldLength < newLength)
{
return true;
}
else
{
return false;
}
}
}//class_end
unity3d 两指缩放
最新推荐文章于 2024-07-29 21:55:23 发布