2,543
社区成员
发帖
与我相关
我的任务
分享
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class NewBehaviourScript : MonoBehaviour ,IBeginDragHandler,IDragHandler
{
private static int moveId;
[SerializeField]
private float rotateSpeed = 5;
private Material material;
private Vector3 oldWorld;
private Vector2 size;
private Vector2 scale;
private Vector3 newWorld;
private Vector3 offset = Vector3.zero;
private Vector2 center = new Vector2(0.5f, 0.5f);
private MeshRenderer meshRenderer;
private Mesh mesh;
private void Awake()
{
mesh = GetComponent<MeshFilter>().mesh;
meshRenderer = GetComponent<MeshRenderer>();
material = meshRenderer.material;
var boundsSize = meshRenderer.bounds.size;
size = new Vector2(boundsSize.x,boundsSize.z);//0
//size = new Vector2(boundsSize.x, boundsSize.y);//x 旋转 -90
//size = new Vector2(boundsSize.y, boundsSize.z);//z 旋转 -90
//size = new Vector2(boundsSize.y, boundsSize.z);//z 旋转 90
//size = new Vector2(boundsSize.x, boundsSize.z);//x 旋转 -180
RotateUV(rotateSpeed);
}
void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
{
oldWorld = eventData.pointerCurrentRaycast.worldPosition;
scale = material.GetTextureScale("_MainTex");
moveId = GetInstanceID();
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
if (moveId != GetInstanceID()) return;
if (eventData.pointerEnter == null) return;
newWorld = eventData.pointerCurrentRaycast.worldPosition;
offset += newWorld - oldWorld;
material.SetTextureOffset("_MainTex", new Vector2(offset.x* scale.x / size.x, offset.z* scale.y/ size.y));
//material.SetTextureOffset("_MainTex", new Vector2(offset.x * scale.x / size.x, offset.y * scale.y / size.y));
//material.SetTextureOffset("_MainTex", new Vector2(-offset.y * scale.x / size.x, offset.z * scale.y / size.y));
//material.SetTextureOffset("_MainTex", new Vector2(offset.y * scale.x / size.x, offset.z * scale.y / size.y));
//material.SetTextureOffset("_MainTex", new Vector2(offset.x * scale.x / size.x, -offset.z * scale.y / size.y));
oldWorld = newWorld;
}
/// <summary>
/// 旋转uv
/// </summary>
/// <param name="angle"></param>
public void RotateUV(float angle)
{
angle = angle * Mathf.Deg2Rad;
List<Vector2> uvs = new List<Vector2>(mesh.uv);
for (int i = 0; i < uvs.Count; i++)
{
Vector2 uv = uvs[i] - center;
uv = new Vector2(uv.x * Mathf.Cos(angle) - uv.y * Mathf.Sin(angle),
uv.x * Mathf.Sin(angle) + uv.y * Mathf.Cos(angle));
uv += center;
uvs[i] = uv;
}
mesh.SetUVs(0, uvs);
}
}