平行于视口平面的3D物体拖拽
2016-03-10 本文已影响115人
影子丢了
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Drag3DBase : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler {
bool drag = false;
float distance;
Vector3 originPointPos;
Vector3 originObjPos;
//垂直于拖拽平面的长度
float VerticalLineLength;
public void OnBeginDrag(PointerEventData eventData)
{
if (eventData.rawPointerPress.transform == this.transform)
{
drag = true;
distance = eventData.pointerPressRaycast.distance;
VerticalLineLength = GetVerticalLine(eventData.position, distance);
originPointPos = GetWorldPos(eventData.position, distance);
originObjPos = this.gameObject.transform.position;
OnBeginDragHandle(eventData);
}
}
public void OnDrag(PointerEventData eventData)
{
if (!drag)
return;
Vector3 tempPos = GetWorldPos(eventData.position, GetDragDistance(eventData.position));
Vector3 deltaPos = tempPos - originPointPos;
this.transform.position = (originObjPos + deltaPos);
OnDragHandle(eventData);
}
public void OnEndDrag(PointerEventData eventData)
{
if (!drag)
return;
drag = false;
OnEndDragHandle(eventData);
}
protected Vector3 GetWorldPos(Vector2 mousePos, float distance)
{
Ray ray = Camera.main.ScreenPointToRay(mousePos);
return ray.GetPoint(distance);
}
/// <summary>
/// 获取拖拽平面垂线的长度
/// </summary>
/// <param name="mousePos"></param>
/// <param name="distance"></param>
/// <returns></returns>
float GetVerticalLine(Vector2 mousePos,float distance)
{
Ray objRay = Camera.main.ScreenPointToRay(mousePos);
Ray vertical = Camera.main.ScreenPointToRay(new Vector2(Screen.width/2,Screen.height/2));
Vector3 objDir = objRay.direction;
Vector3 verticalLineDir = vertical.direction;
float angle = Vector3.Angle(objDir, verticalLineDir);
return distance * Mathf.Cos(angle * Mathf.Deg2Rad);
}
/// <summary>
/// 获取拖拽物体的射线长度
/// </summary>
/// <param name="mousePos"></param>
/// <returns></returns>
float GetDragDistance(Vector2 mousePos)
{
Ray vertical = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
Ray objRay = Camera.main.ScreenPointToRay(mousePos);
Vector3 objDir = objRay.direction;
Vector3 verticalLineDir = vertical.direction;
float angle = Vector3.Angle(objDir, verticalLineDir);
return VerticalLineLength / Mathf.Cos(angle * Mathf.Deg2Rad);
}
protected virtual void OnBeginDragHandle(PointerEventData eventData)
{
}
protected virtual void OnDragHandle(PointerEventData eventData)
{
}
protected virtual void OnEndDragHandle(PointerEventData eventData)
{
}
}