public Vector3 pos;
public GameObject cube;
private void OnGUI()
{
GUILayout.Label("鼠标点击位置信息" + Input.mousePosition);
GUILayout.Label("鼠标点击的位置" + pos);
}
public Vector3 ScreenToWorld(Vector3 mousePos, Transform targetT)
{
Vector3 dis = targetT.position - Camera.main.transform.position;//获取相机与物体之间的差值
Vector3 nomalDir = Vector3.Project(dis, Camera.main.transform.forward);//通过差值,可以获取与相机正前方的投影面(矩形框)
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, nomalDir.magnitude));//获取相机的长度
return pos;//返回一个位置
}
private void Update()
{
pos = ScreenToWorld(Input.mousePosition, cube.transform);
if (Input.GetMouseButtonDown(0))
{
cube.transform.position = pos;
if (Input.GetMouseButton(0))
{
cube.transform.position = pos;
}
}
}
2020-7-7 15-21-33.JPG
public GameObject parent;
public GameObject sun;
private void OnGUI()
{
GUI.Label(new Rect(40, 40, 200, 20), "方块的世界坐标" + parent.transform.position);
GUI.Label(new Rect(40, 60, 200, 20), "圆球的世界坐标" + sun.transform.position);
GUI.Label(new Rect(40, 80, 200, 20), "方块的自身坐标" + parent.transform.localPosition);
GUI.Label(new Rect(40, 100, 200, 20), "圆球的自身坐标" + sun.transform.localPosition);
if (GUILayout.Button("转换"))
{
Debug.Log("圆球的世界坐标是:" + parent.transform.TransformPoint(sun.transform.localPosition));
Debug.Log("圆球的自身坐标是:" + parent.transform.InverseTransformPoint(sun.transform.position));
}
}