using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MouseDrag : MonoBehaviour
{
public Transform tfOriginPanel;
public Transform tfColliderParent;
public Text txtHorizontal;
public Text txtVertical;
Vector3 startPos;
Vector3 endPos;
Vector3 offset;
bool isStop;
public bool IsStop {
get {
return isStop;
}
set {
isStop = value;
if (!isStop)
{
//外部禁止移动放开时,重新设置一下起点
startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
}
}
}
void Start()
{
}
private void Update()
{
if (isStop)
return;
if (Input.GetMouseButtonDown(0))
{
startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
}
if (Input.GetMouseButton(0))
{
endPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
//计算偏移量
offset = endPos - startPos;
//让cube按照x,z轴移动
offset = new Vector3(offset.x, 0, offset.y);
//让cube移动
tfOriginPanel.position += offset;
tfColliderParent.position = tfOriginPanel.position;
//这一次拖拽的终点变成了下一次拖拽的起点
startPos = endPos;
}
}
Vector3 MyScreenPointToWorldPoint(Vector3 ScreenPoint, Transform target)
{
//得到物体在主相机的某个方向
Vector3 dir = (target.position - Camera.main.transform.position);
//计算投影
Vector3 norVec = Vector3.Project(dir, Camera.main.transform.forward);
return Camera.main.ViewportToWorldPoint(
new Vector3(
ScreenPoint.x / Screen.width,
ScreenPoint.y / Screen.height,
norVec.magnitude
)
);
}
/*
* 可选,用下面两个事件时,屏蔽掉update里的所有代码,且只能拖动物体本身
private void OnMouseDown()
{
startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
}
private void OnMouseDrag()
{
endPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
//计算偏移量
offset = endPos - startPos;
//让cube按照x,z轴移动
offset = new Vector3(offset.x, 0, offset.y);
//让cube移动
tfOriginPanel.position += offset;
tfColliderParent.position = tfOriginPanel.position;
//这一次拖拽的终点变成了下一次拖拽的起点
startPos = endPos;
}
*/
}
unity 拖动cube 2D屏幕坐标转3D世界坐标
猜你喜欢
转载自blog.csdn.net/cuijiahao/article/details/109538084
今日推荐
周排行