?这三个方法都是没有优化过的方法,鼠标点到物体的时候物体的中心点会跳到鼠标点的位置,从一开始写的方法三理解之后慢慢删代码最后变成了方法一。。。。。。。。
public class 箭头 : MonoBehaviour
{
private bool 拖拽 = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
方法一::::::::::::::::::::::::::::::::::::::::::::::
Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Mouseposition.z = 0;
float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
if (Input.GetMouseButton(0) && (Distance < 1.5f))
{
this.gameObject.transform.position = Mouseposition;
}
方法二::::::::::::::::::::::::::::::::::::::::::::::
Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Mouseposition.z = 0;
if (Input.GetMouseButton(0))
{
float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
if (Distance < 1.5f)
{
this.gameObject.transform.position = Mouseposition;
}
}
方法三::::::::::::::::::::::::::::::::::::::::::::::
Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Mouseposition.z = 0;
if (Input.GetMouseButton(0))
{
float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
if (Distance < 1.5f)
{
拖拽 = true;
}
}
else
{
拖拽 = false;
}
if (拖拽)
{
this.gameObject.transform.position = Mouseposition;
}
}
}
下面是在方法三下实现不跳动的物体拖拽方法:::::::
public class 箭头 : MonoBehaviour
{
private bool 拖拽 = false;
private Vector3 LasteMousePosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 Mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Mouseposition.z = 0;
//首先声明鼠标位置
if (Input.GetMouseButtonDown(0))
{
float Distance = (this.gameObject.transform.position - Mouseposition).magnitude;
if (Distance < 1.2f)
{
拖拽 = true;
LasteMousePosition = Mouseposition;
//鼠标最后位置等于鼠标位置(下面要用到)
}
}
else if(Input.GetMouseButtonUp(0))
{
拖拽 = false;
}
if (拖拽)
{
Vector3 DeltaVec = Mouseposition-LasteMousePosition;
//鼠标位置与物体位置的相对向量
this.gameObject.transform.position += DeltaVec;
//鼠标当前位置加上两者之间一开始的相对位置,得到鼠标移动位置,从而取代物体从自身中心点向鼠标移动的向量
LasteMousePosition = Mouseposition;
//最后再对鼠标的最后位置进行更新,否则将会沿着鼠标移动方向一直移动
}
}
}
实现鼠标拖拽物体
|