Unity实现2D物体拖拽效果
程序员文章站
2022-07-13 22:29:59
...
Unity实现2D物体拖拽效果
方法1:简单粗暴,给物体上挂上一个拖拽脚本,实现OnMouseDrag()方法,上图
方法2:给物体上挂上一个拖拽脚本,实现接口IDragHandler,上图、
方法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:有待添加
上一篇: day6