实现鼠标拖动大图查看

2017-11-08  本文已影响0人  带着面包去流浪

1、使用UGUI实现

2、创建Image

3、Image上绑定脚本,代码如下:


using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.EventSystems;

public class ImageDrag : MonoBehaviour, IBeginDragHandler, IDragHandler

{

    //鼠标第一次点击的位置

    Vector2 firstMousePos = Vector3.zero;

    //鼠标拖拽的位置

    Vector2 secondMousePos = Vector3.zero;

    //偏移量

    Vector3 offsetPos = Vector3.zero;

    public void OnBeginDrag(PointerEventData eventData)

    {

        firstMousePos = Input.mousePosition;

    }

    public void OnDrag(PointerEventData eventData)

    {

        secondMousePos = Input.mousePosition;

        //需要移动的 向量

        offsetPos = secondMousePos - firstMousePos;

        float x = transform.localPosition.x;

        float y = transform.localPosition.y;

        //向量偏移

        x = x + offsetPos.x; y = y + offsetPos.y;

        //x = Mathf.Clamp(x, 380, 1550);

        //y = Mathf.Clamp(y, 210, 850);

        transform.localPosition = new Vector3(x, y, transform.localPosition.z);

        firstMousePos = secondMousePos;

    }

}


也可以使用EventTrigger组件(鼠标拖动事件)实现

绑定一下事件

上一篇 下一篇

猜你喜欢

热点阅读