简体   繁体   中英

Drag a UI Image in Unity3d (C#)

I need to make a map in UI . Map is big so user needs to zoom and drag it. For zoom now I use this:

public class ScaleMaps : MonoBehaviour
{
    private float zoom;
    public float zoomSpeed;
    public Image map;

    public float zoomMin;
    public float zoomMax;

    void Update()
    {
        zoom = (Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomSpeed);
        map.transform.localScale += new Vector3(map.transform.localScale.x * zoom, map.transform.localScale.y * zoom, 0);
        Vector3 scale = map.transform.localScale;
        scale = new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0);
        map.transform.localScale = scale;
    }
}

How to drag the image with mouse ?

Have you tried the IDragHandler interface?

public class UIDraggable : MonoBehaviour, IDragHandler {


#region IDragHandler implementation

public void OnDrag (PointerEventData eventData)
{
    this.transform.position += (Vector3)eventData.delta;
}

#endregion
}

You will need to include the following at the top of your script..

using UnityEngine.EventSystems;

Based on Ben's answer, I changed it a bit to work better with UI elements:

[RequireComponent(typeof(RectTransform))]
public class Draggable : MonoBehaviour, IDragHandler
{
    private RectTransform rectTransform;

    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM