鼠标拖动 uv,加入旋转量后不会计算了

小鱼游戏开发 2018-04-14 03:47:57
如果uv旋转了,如何计算?
如果物体也旋转了,如何计算?

就是说,需要计算 uv 和 物体 的旋转。

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);
}
}
...全文
471 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

2,543

社区成员

发帖
与我相关
我的任务
社区描述
Unity3D相关内容讨论专区
游戏unity 技术论坛(原bbs)
社区管理员
  • Unity3D
  • 芝麻粒儿
  • 「已注销」
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

Unity3D社区公告:

  1. 社区致力于解决各种Unity3D相关的“疑难杂症”。
  2. 社区不允许发布与Unity3D或相关技术无关内容。
  3. 社区版主邀请各位一道为打造优秀社区不懈努力。

试试用AI创作助手写篇文章吧