//C#脚本如下,将脚本挂在物体上即可
Zoom.cs
using UnityEngine;
public class Zoom : MonoBehaviour
{
//旧的触摸点位置
Vector2 oldPos1;
Vector2 oldPos2;
// 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.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))
{
//获取transform组件缩放属性x轴数值
float oldScale = transform.localScale.x;
//新的数值为旧的数值放大1.025倍
float newScale = oldScale * 1.025f;
//将新的值赋给transform组件缩放属性
transform.localScale = new Vector3(newScale, newScale, newScale);
}
else //如果触摸手势为缩小,同理缩小1.025倍
{
float oldScale = transform.localScale.x;
float newScale = oldScale / 1.025f;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
//新的位置覆盖旧的位置
oldPos1 = newPos1;
oldPos2 = newPos2;
}
}
}
//判断手势是否为放大手势
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;
}
}
}