1. 程式人生 > >地圖放大縮小,以兩指中間的點為錨點

地圖放大縮小,以兩指中間的點為錨點

  1. 地圖放大縮小,以兩指中間的點為錨點 
  2. 該程式碼使用外掛Easy Touch ,DoTween
using DG.Tweening;
using UnityEngine;
using HedgehogTeam.EasyTouch;

public class MapFixedPointZoom  : MonoBehaviour
{
    public float MaxScale = 1.5f;
    public float MinScale = 1f;
    public RectTransform Map;
    public RectTransform Canvas;
    public RectTransform People;
    public void OnEnable()
    {
        EasyTouch.On_Pinch += On_Pinch;
        //EasyTouch.On_Drag += On_Drag;
    }

    public void OnDestroy()
    {
        EasyTouch.On_Pinch -= On_Pinch;
        //EasyTouch.On_Drag -= On_Drag;
    }


    private void On_Drag(Gesture gesture)
    {
        XYLimit();
    }

    public void OnDrap()
    {
        XYLimit();
    }

    public void Tap()
    {
        var pos = ScreenPos2MapPos(Input.mousePosition);
        People.DOLocalMove(pos, 0.5f);
    }

    private void On_Pinch(Gesture gesture)
    {
        FixedPointZoom(gesture.deltaPinch * gesture.deltaTime * 0.2f, gesture.position);
    }

    private void FixedPointZoom(float scaleChangeValue, Vector2 screenPos)
    {
        float delX = screenPos.x - Map.position.x;
        float delY = screenPos.y - Map.position.y;

        float scaleX = delX / Map.rect.width / Map.localScale.x;
        float scaleY = delY / Map.rect.height / Map.localScale.y;

        Map.localScale = new Vector2(Mathf.Clamp(Map.localScale.x + scaleChangeValue, MinScale, MaxScale),
            Mathf.Clamp(Map.localScale.y + scaleChangeValue, MinScale, MaxScale));

        Map.pivot += new Vector2(scaleX, scaleY);
        Map.position += new Vector3(delX, delY, 0);
        XYLimit();
    }
    private void XYLimit()
    {
        var minX = Map.sizeDelta.x * Map.localScale.x * (Map.pivot.x - 1) + Canvas.sizeDelta.x;
        var maxX = Map.sizeDelta.x * Map.localScale.x * Map.pivot.x;
        var x = Mathf.Clamp(Map.localPosition.x, minX, maxX);
        var minY = Map.sizeDelta.y * Map.localScale.y * (Map.pivot.y - 1);
        var maxY = Map.sizeDelta.y * Map.localScale.y * Map.pivot.y - Canvas.sizeDelta.y;
        var y = Mathf.Clamp(Map.localPosition.y, minY, maxY);
        Map.localPosition = new Vector3(x, y, 0);
    }

    private Vector2 ScreenPos2MapPos(Vector2 screenPos)
    {
        //父類的pivot影響子類的 不用處理
        var x = (-Map.localPosition.x + screenPos.x) / Map.localScale.x;
        var y = -(Canvas.sizeDelta.y - screenPos.y + Map.localPosition.y) / Map.localScale.y;
        return new Vector2(x, y);
    }
}