Unity实现2D物体拖拽效果
方法1:简单粗暴,给物体上挂上一个拖拽脚本,实现OnMouseDrag()方法,上图
方法2:给物体上挂上一个拖拽脚本,实现接口IDragHandler,上图 (经过新的测试,好像只能用于UI对象)、
方法3:直接上代码
void Update()
{
if (Input.GetMouseButtonDown(0))
{
isMouseDown = true;
}
if (Input.GetMouseButtonUp(0))
{
isMouseDown = false;
lastMousePosition = Vector3.zero;
isClickObj = false;
}
if (isMouseDown)
{
RaycastHit2D raycastHit2D =
Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 100);
Debug.Log(raycastHit2D.collider);
if (raycastHit2D.collider != null)
{
if (raycastHit2D.collider.transform == transform)
{
isClickObj = true;
}
}
if (isClickObj)
{
Move();
}
}
}
private void Move()
{
if (lastMousePosition != Vector3.zero)
{
Vector3 offset = Camera.main.ScreenToWorldPoint(Input.mousePosition) - lastMousePosition;
this.transform.position += offset;
}
lastMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
方法4:使用FingerGestures插件来实现拖拽
注意,场景中要拖入FingerGestures手势检测预制体,物体上挂DragRecognizer和ScreenRaycaster脚本
方法5:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Collider2D))]
public class DragObject : MonoBehaviour
{
public Vector2 _DragScale = Vector2.one;
[HideInInspector]
public Vector3 _CurrentPos = Vector3.zero;
protected Transform m_Transform;
protected Plane m_Plane;
protected bool m_Started = false;
protected bool m_Pressed = false;
protected Vector3 m_LastPos;
protected int m_TouchID = 0;
protected virtual void OnEnable()
{
m_Transform = transform;
}
protected virtual void OnDisable()
{
m_Started = false;
}
protected virtual void OnPress(bool isDown)
{
DebugTool.Log("OnPress: " + isDown);
if (isDown)
{
if (!m_Pressed)
{
m_TouchID = UICamera.currentTouchID;
m_Pressed = true;
m_Started = false;
Transform trans = UICamera.currentCamera.transform;
m_Plane = new Plane(trans.rotation * Vector3.back, UICamera.lastWorldPosition);
}
}
else if (m_Pressed && m_TouchID == UICamera.currentTouchID)
{
m_Pressed = false;
}
}
protected virtual void OnDrag(Vector2 delta)
{
if (m_Pressed && m_TouchID == UICamera.currentTouchID && enabled)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
Ray ray = UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos);
float dist = 0f;
if (m_Plane.Raycast(ray, out dist))
{
_CurrentPos = ray.GetPoint(dist);
Vector3 offset = _CurrentPos - m_LastPos;
m_LastPos = _CurrentPos;
if (!m_Started)
{
m_Started = true;
offset = Vector3.zero;
}
if (offset.x != 0f || offset.y != 0f)
{
offset = m_Transform.InverseTransformDirection(offset);
offset.Scale(_DragScale);
offset = m_Transform.TransformDirection(offset);
}
m_Transform.position += offset;
}
}
}
}
该方法需要NGUI相机搭配使用,不推荐,下图是NGUI相机配置
注意:这里的UICamera必须选择2D类型