Unity AR 两指手势实现物体放大缩小功能

admin2年前unity基础API514
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;
        }
    }
}


相关文章

相机跟随角色移动镜头缩放方法

这种方法最简单可以实现相机跟随角色平移1:计算相机和目标物体的距离  offset = this.transform.position - ...

Unity寻找子物体的几种方法

    1: transform.Find()寻找子物体   transform.Find(“子物体名字”)2: GameObject.FindGam...

Unity移动操作物体

if (Input.touchCount == 1)         {  ...

通过刚体移动的方法

1:MovePosion移动的新的位置,传入的参数是最新的位置 一般是旧的位置加上变化的参数2:velocity这个方法是瞬间给物体一个恒定的速度,将物体提升至该速度 3:addF...

Unity给UI元素物体添加操作响应事件

可以给自定义物体如图片等添加响应事件引入命名空间using UnityEngine.EventSystems;类中继承接口IPointerDownHandler实现接口  ...

利用射线获取被点击的物体信息

首先被点击的物体需要加上碰撞体Collider监听点击代码:鼠标点击:if (Input.GetMouseButtonDown(0))     &n...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。