unity实现双指缩放,并且让缩放位置保持不变

手游中经常会用到双指缩放的操作。双指缩放的逻辑很简单,只需要根据双指当前距离和双指刚按下时记录的距离进行比例缩放就可以了。

缩放位置不变稍微麻烦点,但是理解了思路就好做了,其实就是让两指中点与目标原点距离保持初始距离*缩放倍数。比如说原本距离是1,现在缩放了1.5倍那么距离就变成1.5。具体参照下面代码。

public class ScaleByTwoFinger : MonoBehaviour
{
    public Transform target; //目标
    bool isInit;
    Vector3 touch1, touch2,oriPos,pos;
    float scale, disX, disY, oriScale;
    public float scaleSpeed = 1;

    public bool isLimitScale;
    public float min, max;

    private void Update()
    {
    	//不是双指就关闭
        if(Input.touchCount != 2)
        {
            isInit = false;
        }

		//初始化
        if(Input.touchCount == 2 && !isInit)
        {
			//两指点位
            touch1 = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            touch2 = Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position);

			//目标初始点位
            oriPos = new Vector3(transform.position.x, transform.position.y, 0);
			
			//两指中点
            pos = new Vector3((Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).x + Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position).x) / 2, (Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).y + Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position).y) / 2, 0);

			//两指中点和目标距离
            disX = pos.x - oriPos.x;
            disY = pos.y - oriPos.y;
            oriScale = transform.localScale.x;


            isInit = true;
        }

		if(Input.touchCount == 2)
        {
        	//两指缩放比例
            scale = Vector3.Distance(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position)) / Vector3.Distance(touch1, touch2);

			//利用scaleSpeed控制缩放速度
            scale = (scale - 1) * scaleSpeed;

			//给缩放比例加限制
            if (isLimitScale && target.localScale.x <= min && scale < 0)
                return;
            if (isLimitScale && target.localScale.x >= max && scale > 0)
                return;
			
			//缩放目标大小
            target.localScale = new Vector3(oriScale + scale, oriScale + scale, oriScale + scale); 
			//改变目标位置,让位置保持不变
            transform.position = new Vector3(oriPos.x - ((target.localScale.x - oriScale) * disX), oriPos.y - ((target.localScale.y - oriScale) * disY), 0);
        }
    }
}

你可能感兴趣的:(Unity学习,unity,unity3d,c#,游戏开发)