unity 拖拽 uv

部分函数在https://blog.csdn.net/qq_17813937/article/details/79950879


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PlaneUVOperation : MonoBehaviour, IBeginDragHandler, IDragHandler
{
    private float currentAngle = 0;
    private Mesh mesh;
    private Material material;
    private Vector2 size;

    private Vector4 offset;
    private Vector2 actualOffset;
    private Vector2 scale;
    private Vector2 result;
    private Vector3 oldPos;
    private Vector3 newPos;

    private Matrix4x4 uvRotate;
    private Matrix4x4 matRotate;
    private Vector2 textureSize;
    
    private void Awake()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        material = GetComponent<MeshRenderer>().material;
        var texture = material.GetTexture("_MainTex");
        textureSize = new Vector2(texture.width,texture.height);
        scale = material.GetTextureScale("_MainTex");

        #region 计算Plane实际大小
        var boundsSize = mesh.bounds.size;
        size = new Vector2(boundsSize.x,boundsSize.z);
        size.Scale(new Vector2(transform.localScale.x,transform.localScale.z));
        #endregion

    }

    public void RotateUV(float angle)
    {
        currentAngle += angle;
        mesh.RotateUV(angle);
    }

    public void Scale(Vector2 size)
    {
        scale = size;
        material.SetTextureScale("_MainTex", size);
    }

    public void Tiling(int count)
    {
        material.SetTextureScale("_MainTex", new Vector2(count,count));
    }

    public void SetNativeSize()
    {
        material.SetTextureScale("_MainTex", new Vector2(size.x / textureSize.x, size.y / textureSize.y));
    }

    void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
    {
        matRotate = Matrix4x4.Rotate(transform.localRotation).transpose;
        oldPos = eventData.pointerCurrentRaycast.worldPosition;
        uvRotate = uvRotate.Rotate2D(currentAngle);
    }
    
    void IDragHandler.OnDrag(PointerEventData eventData)
    {
        if (eventData.pointerEnter == null) return;

        newPos = eventData.pointerCurrentRaycast.worldPosition;

        // 旋转为欧拉角 (0,0,0) 计算偏移
        offset += (matRotate * newPos) - (matRotate * oldPos);
        //设置偏移
        actualOffset.Set(offset.x, offset.z);

        //旋转uv
        actualOffset = uvRotate * actualOffset;
        
        //平移
        result.Set(actualOffset.x * scale.x / size.x, actualOffset.y * scale.y / size.y);

        material.SetTextureOffset("_MainTex", result);
        oldPos = newPos;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17813937/article/details/79946042
Uv